1

我需要能够使用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构建器吗?

另外,我将如何通过人际关系来做到这一点?

例如,如果我的评论与名为comment_location 的表有关系,并且我想对whereRaw评论位置关系做一个这样的

foreach($user->comments as $comment){
  foreach($comment->commentLocation->whereRaw() as $location){
    echo $location->name;
  }
}
4

1 回答 1

2

您正在使用$user->comments哪个实例,Illuminate\Database\Eloquent\Collection但您应该使用$user->comments()哪个实例,Illuminate\Database\Eloquent\Relations\BelongsToMany您可以添加查询构建器功能

固定代码:

foreach($user->comments()->whereRaw('DATE(comment_date) = DATE(NOW())')->get() as $comment) {
   echo $comment->content;
}
于 2018-06-12T16:23:38.363 回答