【问题标题】:Using whereRaw on pivot relationship model在枢轴关系模型上使用 whereRaw
【发布时间】: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


【解决方案1】:

您正在使用$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;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 2014-08-17
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2019-07-05
相关资源
最近更新 更多