在枢轴关系模型上使用 whereRaw
Using whereRaw on pivot relationship model
我需要能够在枢轴 table 关系上使用 whereRaw
来获取今天的所有数据。
例如,这是我的模型
public function comments(){
return $this->belongsToMany('App\Models\Comments', 'user_comments', 'user_id', 'comment_id');
}
效果很好,它为我提供了我需要的所有数据。
但是我该如何在这个模型上使用 whereRaw
语句呢?因此,如果我需要遍历今天创建的每条评论,但评论日期字段以 Y-m-d H:i:s
格式存储,所以我需要 trim 关闭时间,我该怎么做?尝试做这样的事情
foreach($user->comments->whereRaw('DATE(comment_date) = DATE(NOW())') as $comment){
echo $comment->content;
}
但它只是 returns
[BadMethodCallException]
Method whereRaw does not exist.
whereRaw
生成器不能这样使用吗?
此外,我将如何通过人际关系做到这一点?
例如,如果我的评论与一个名为 comment_location 的 table 有关系,我想对评论位置关系做一个 whereRaw
,就像这样
foreach($user->comments as $comment){
foreach($comment->commentLocation->whereRaw() as $location){
echo $location->name;
}
}
您正在使用 $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;
}
我需要能够在枢轴 table 关系上使用 whereRaw
来获取今天的所有数据。
例如,这是我的模型
public function comments(){
return $this->belongsToMany('App\Models\Comments', 'user_comments', 'user_id', 'comment_id');
}
效果很好,它为我提供了我需要的所有数据。
但是我该如何在这个模型上使用 whereRaw
语句呢?因此,如果我需要遍历今天创建的每条评论,但评论日期字段以 Y-m-d H:i:s
格式存储,所以我需要 trim 关闭时间,我该怎么做?尝试做这样的事情
foreach($user->comments->whereRaw('DATE(comment_date) = DATE(NOW())') as $comment){
echo $comment->content;
}
但它只是 returns
[BadMethodCallException]
Method whereRaw does not exist.
whereRaw
生成器不能这样使用吗?
此外,我将如何通过人际关系做到这一点?
例如,如果我的评论与一个名为 comment_location 的 table 有关系,我想对评论位置关系做一个 whereRaw
,就像这样
foreach($user->comments as $comment){
foreach($comment->commentLocation->whereRaw() as $location){
echo $location->name;
}
}
您正在使用 $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;
}