【发布时间】:2018-11-22 02:57:20
【问题描述】:
我需要能够在数据透视表关系上使用whereRaw 来获取今天的所有数据。
例如,这是我的模型
public function comments(){
return $this->belongsToMany('App\Models\Comments', 'user_comments', 'user_id', 'comment_id');
}
效果很好,它为我提供了我需要的所有数据。
但是我如何在这个模型上使用whereRaw 声明呢?因此,如果我需要遍历今天创建的每条评论,但评论日期字段以Y-m-d H:i:s 格式存储,所以我需要修剪时间,我该怎么做?尝试做这样的事情
foreach($user->comments->whereRaw('DATE(comment_date) = DATE(NOW())') as $comment){
echo $comment->content;
}
但它只是返回
[BadMethodCallException]
方法 whereRaw 不存在。
不能像这样使用whereRaw builder吗?
另外,我将如何通过人际关系来做到这一点?
例如,如果我的 cmets 与一个名为 comment_location 的表有关系,并且我想对这样的评论位置关系执行whereRaw
foreach($user->comments as $comment){
foreach($comment->commentLocation->whereRaw() as $location){
echo $location->name;
}
}
【问题讨论】:
-
试试
$user->comments()->whereRaw...。在 cmets 之后注意() -
$comment->commentLocation 转换为 $comment->comment_location()
标签: php laravel laravel-5 eloquent query-builder