【发布时间】:2020-05-10 18:49:54
【问题描述】:
我有以下 3 个表:
- 帖子
- 评论
- 标签
帖子:
class Post extends Eloquent
{
public function comments()
{
return $this->hasMany(Comment::class,'post_id','id');
}
}
** Post data **
{
'id' : 1,
'title' : 'bla bla',
'created_at: 'some date'
}
评论:
class Comment extends Eloquent
{
public function comments()
{
return $this->belongsTo(Post::class,'id');
}
public function tags()
{
return $this->hasMany(Tag::class,'id','tags_ids');
}
}
** Comments data **
{
'id' : 322,
'active' : true
'post_id' : 1,
'created_at: 'some date',
'tags_ids' : [1,2,3]
}
标签:
class Tag extends Eloquent
{
public function tags()
{
return $this->belongsTo(Comment::class,'tags_ids');
}
}
** Tags data **
{
{'id' : 1,
'description' : 'some description1'
},
{'id' : 2,
'description' : 'some description2'
},
{'id' : 3,
'description' : 'some description3'
}
}
post 表有很多 cmets,cmets 表有很多与之关联的标签。
如何使用预先加载将所有这些表放在一起?
类似:
$post = Post::where('id',1)->with(['comments' => function($q) {
$q->with('tags');
}])->first();
但是这个查询总是在标签关系中返回空响应。
我做错了什么?
想要的结果是这样的:
{
'id' : 1,
'title' : 'bla bla',
'created_at: 'some date',
'comments':[{
'id' : 322,
'active' : true
'post_id' : 1,
'created_at: 'some date',
'tags_ids' : [1,2,3],
'tags' : [
{'id' : 1,'description' : 'some description1'},
{'id' : 2, 'description' : 'some description2'},
{'id' : 3,'description' : 'some description3'}
],
}
]
}
你可以看到post里面有cmets,cmets里面也有tags关系。
附:我在我的项目中使用了“jenssegers/laravel-mongodb”包,我试图在没有任何原始表达式的情况下做到这一点。
谢谢。
【问题讨论】:
-
请添加您的 3 个表结构
-
cmets和tags的关系是1-n?然后标签表中缺少字段comment_id。但是你应该考虑一个 n-m 关系。
标签: php laravel mongodb eloquent eager-loading