我知道这是可能的,也许我已经做到了,我需要刷新我的记忆。假设我们有一对多
$post->comments
我想要 对此帖子的评论,其中评论日期晚于特定日期。我不想在 php 值中获取这个特定日期。因为我想用它作为通用列名。
$myComments = $post->comments->where('published', '>=', 'posts.updated_at');
我做了类似的事情,但我得到了
未找到列
谢谢
您遇到了 3 个问题:
首先,
$post->comments
是一个Collection
,根本不使用SQL,所以posts.updated_at
将不可用,但$post->updated_at
可用。
其次,关系不使用
joins
,因此 posts.updated_at
将不可用,除非您手动加入它。
第三,
->where()
是 string
匹配,因此您的查询实际上是 WHERE published = 'projects.updated_at'
,它将返回 0
结果。您需要在那里使用 ->whereColumn()
。
您可以通过带有
where()
子句的“预加载”评论来解决此问题:
$post = Post::with(['comments' => function ($query) {
return $query->select('comments.*')
->join('posts', 'comments.post_id', '=', 'posts.id')
->whereColumn('comments.published', '>=', 'posts.updated_at');
})->first();
// Or `$posts = Post::with([ /* ... */ ])->get();
或者保留
->comments
语法,但传递属性,而不是 SQL 字段:
$myComments = $post->comments->where('published', '>=', $post->updated_at)
或者最后,使用
->comments()
,其语法与预加载相同:
$myComments = $post->comments()
->select('comments.*')
->join('posts', 'comments.post_id', '=', 'posts.id')
->whereColumn('comments.published', '>=', 'posts.updated_at')
->get();