![](/img/trans.png)
[英]Laravel Eloquent ORM: trouble with one-to-many using belongs_to()
[英]One-to-many then eager load an array with Laravel Eloquent ORM
使用Laravel和雄辯的ORM,我想創建屬於特定用戶(登錄的用戶)的所有帖子和相應評論的數組或對象。 然后結果將與Response :: eloquent()一起使用; 返回JSON。
基本上在偽代碼中:
All Posts by user ::with('comments').
要么
Posts by Auth::user()->id ::with('comments').
我通常使用用戶的表,注釋表和帖子表進行數據庫設置。 comments表有一個post_id,posts表有一個user_id。
在沒有Laravel的情況下做這件事的漫長道路將是:
SELECT * FROM posts WHERE user_id = 'user_id'
foreach($result as $post) {
SELECT * FROM comments WHERE posts_id = $post->id
foreach($query as $comment) {
$result[$i]->comments[$n] = $comment
}
}
但我想用Laravel的Eloquent ORM來實現它。
看起來你甚至不需要嵌套的eager load,你只需要修改帶有return的查詢,所以:
$posts = Post::with('comments')->where('user_id', '=', 1)->get();
您可以菊花鏈式連接Eloquent系統中的大多數方法,通常它們只返回一個Fluent查詢對象。
(我沒有對它進行過測試,但我相當肯定它會工作。另外,你不能在:: all()上執行它,因為它會為你調用 - > get()。你必須深入挖掘源代碼代碼找到這個,我不認為Eloquent文檔提到它正在做的事情。)
此外, Eager Loading文檔還包含嵌套的預先加載,因此您可以使用其評論加載所有用戶及其評論:
您甚至可能急於加載嵌套關系。 例如,假設我們的作者模型具有“聯系人”關系。 我們可以從我們的Book模型中急切加載這兩種關系,如下所示:
$books = Book::with(array('author', 'author.contacts'))->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.