2016-02-07 32 views
1

我有postspostWriters表與一對多的關係。 (我也有writers表)。Laravel查詢以獲得至少有一個數組元素的結果?

每篇文章都是由幾位作家合作撰寫的。

我想獲得至少有一位作者寫過的20篇文章。

例如,我跟隨作家:

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

查詢不起作用。

這種方法是否合適?還是應該添加專用表來評估我的結果?

+0

你如何遵循一個作家? –

+0

我有一些表格,其中之一就是下面的表格。我從此表中獲取_ $ arrayOfWriterIds_IFollow_。 – horse

+0

顯示你的數據庫結構和模型,沒有必要爲這個任務做出2個不同的查詢,你可以將它們合併爲1. – Gal

回答

1

如果你們的關係是正確定義,則fillowing代碼應工作:

$posts = Post::whereHas('postWriters', function($query) use($arrayOfWriterIds_IFollow) { 
    $query->whereIn('writer_id', $arrayOfWriterIds_IFollow); 
}) 
->orderBy('submitTimestamp', 'desc') 
->take(20) 
->get(); 
+1

這工作正常! – horse

相關問題