Laravel查询以获得具有至少一个数组元素的结果? [英] Laravel query to get results having at least one element of an array?
本文介绍了Laravel查询以获得具有至少一个数组元素的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有具有一对多关系的posts
和postWriters
表. (我也有writers
表).
I have posts
and postWriters
tables with one-to-many relationships. (I have also writers
table).
每篇文章都是由多位作者共同撰写的.
Each post has been written by several writers collaboratively.
我想获得至少20位我所关注的作家所写的文章.
I want to get first 20 posts which have been written by at least one writer I follow.
例如我关注的作家:
$arrayOfWriterIds_IFollow = [3, 5, 123, 45, ..., 3456] // total 100 ids
查询:
$posts = Post::where(
array( 'postWriters' => function($l) {
$l->whereIn('writer_id', $arrayOfWriterIds_IFollow); // or array(3, 5) for 2 writers..
})
)
->orderBy('submitTimestamp', 'desc')
->take(20)
->get();
查询不起作用.
这种方法合适吗?还是应该添加一个专用表来评估结果?
Is this approach appropriate or should I add a dedicated table to evaluate my results?
推荐答案
如果您的关系定义正确,则应使用以下代码:
If your relationship is defined correctly then the fillowing code should work:
$posts = Post::whereHas('postWriters', function($query) use($arrayOfWriterIds_IFollow) {
$query->whereIn('writer_id', $arrayOfWriterIds_IFollow);
})
->orderBy('submitTimestamp', 'desc')
->take(20)
->get();
这篇关于Laravel查询以获得具有至少一个数组元素的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文