Laravel query to get results having at least one e

2019-02-20 12:40发布

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.

I want to get first 20 posts which have been written by at least one writer I follow.

For example the writers that I follow:

$arrayOfWriterIds_IFollow = [3, 5, 123, 45, ..., 3456] // total 100 ids

The query:

$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();

The query does not work.

Is this approach appropriate or should I add a dedicated table to evaluate my results?

1条回答
虎瘦雄心在
2楼-- · 2019-02-20 13:03

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();
查看更多
登录 后发表回答