3 回答

TA貢獻1804條經驗 獲得超3個贊
你錯誤地定義了你的關系。注釋模型中有 as 數組,但標簽需要多對多關系。要實現這一點,你必須定義一個新表:tags_idscomment-tag
comment-tag
comment_id - unsined big integer
tag_id - unsigned big integer
然后在模型中修改關系,如下所示:Commenttags
class Comment extends Model
{
/**
* The tags that belong to the comment.
*/
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
這種關系的反面是:
class Tag extends Model
{
/**
* The comments that belong to the tag.
*/
public function comments()
{
return $this->belongsToMany('App\Comment');
}
}
然后,對于預先加載嵌套關系,可以使用“dot”語法:
$post = Post::with(['comments', 'comments.tags'])->find(1);
有關詳細信息,請參閱 Laravel 文檔中的多對多關系。

TA貢獻1895條經驗 獲得超3個贊
您可以使用
$post = Post::where('id',1)->with(['comments.tags'])->first();
它將加載所有評論以及評論標簽
鏈接搜索中的引用鏈接 https://laravel.com/docs/6.x/eloquent-relationshipsNested Eager Loading

TA貢獻1757條經驗 獲得超7個贊
更新:您必須修復數據庫架構
表結構如下所示:
- posts
- id
- title
- ...
- comments
- id
- active
- post_id
- created_at
- tags
- id
- description
- comment_id
- created_at
// App\Post
class Post extends Eloquent
{
public function comments()
{
return $this->hasMany(Comment::class,'post_id','id');
}
}
// App\Comment
class Comment extends Eloquent
{
public function post()
{
return $this->belongsTo(Post::class);
}
public function tags()
{
return $this->hasMany(Tag::class);
}
}
//App\Tag
class Tag extends Eloquent
{
public function comment()
{
return $this->belongsTo(Comment::class);
}
}
//...
$post = Post::with(['comments', 'comments.tags'])->find(1);
//...
- 3 回答
- 0 關注
- 126 瀏覽
添加回答
舉報