[英]Laravel hasMany as many hasOne
例如,我有 Post 和 Comment 模型。 當我加載 hasMany 關系時,我想為每個關系項獲取單獨的父項。
Post.php:
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
評論.php:
class Comment extends Model
{
public function comments()
{
return $this->belongsTo('App\Post');
}
}
當我加載帶有評論的帖子時
Post::where('title', 'LIKE', search)
->orWhereHas('comments', function ($query) use ($search) {
$query->where('text', 'LIKE', $search)
})
->paginate();
結果看起來像這樣
[
{
post_id: 1,
comments: [
{
comment_id: 1
post_id: 1
},
{
comment_id: 2
post_id: 1
},
{
comment_id: 3
post_id: 1
},
]
},
...
]
但我需要它看起來像這樣(每個評論的單獨帖子)。
[
{
post_id: 1,
comments: [
{
comment_id: 1
post_id: 1
}
]
},
{
post_id: 1,
comments: [
{
comment_id: 2
post_id: 1
}
]
},
{
post_id: 1,
comments: [
{
comment_id: 3
post_id: 1
}
]
},
...
]
我可以用 Laravel 做嗎?
您現在正在檢索帶有評論的帖子,但據我了解,您實際上想從特定帖子中檢索評論。
唯一的困難是指定從哪些帖子加載評論,但這可能會奏效:
$comments = Comment::whereHas('post', function($query) use ($ids) {
$query->whereIn('post_id', $ids);
})
->with('post')
->get();
(Comment 模型中的兩個小錯誤需要先修復:將函數從
comments()
重命名為
post()
並將其更改為
$this
this
這是一個簡單的 foreach 來測試結果:
foreach ($comments as $comment) {
echo 'Post ' . $comment->post->id . ' comment' . $comment->id . '<br>';
}
如果您絕對需要您在 JSON 數據中顯示的格式的結果,則需要一些額外的工作,但沒有必要這樣做來獲得您在評論中鏈接的圖像中顯示的輸出。
更新(因為用戶改變了問題):
通過評論文本(而不是 post-id)搜索使查詢更加容易; 現在根本不需要嵌套查詢:
$comments = Comment::where('text', 'like', '%' . $search . '%')
->with('post')
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.