我正在使用laravel 5.5.13。
我App\Entity
有App\Comment
个App\Thumb
个,public function show(Entity $entity)
{
return $entity->load('comments')->load('thumbs');
}
个。{/ p>
现在我可以像这样轻松地获取评论和拇指:
{
"id": 1,
"kind": null,
"name": "three",
"created_at": "2017-11-01 04:29:22",
"updated_at": "2017-11-01 04:29:22",
"comments": [
{
"id": 5,
"body": "no non o",
"displayname_id": 4,
"entity_id": 1,
"created_at": "2017-11-01 05:16:14",
"updated_at": "2017-11-01 05:16:14"
}
],
"thumbs": [
{
"id": 9,
"like": 0,
"displayname_id": 5,
"entity_id": 1,
"created_at": "2017-11-01 05:16:39",
"updated_at": "2017-11-01 05:16:39"
}
]
}
这提供了这样的数据:
$comment->displaynames()
但是,我还需要$thumb->displaynames()
和App\Vote
的列表,并且每个评论通过$comment->votes()
都有很多{
// removed for concise (same as above)
"comments": [
{
// removed for concise (same as above)
"votes": [
..... // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<< I want to get this
]
},
{
// removed for concise (same as above)
"votes": [
..... // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<< I want to get this
]
}
],
"thumbs": [
{
// removed for concise (same as above)
}
],
"displaynames": [
..... // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<< I want to get this
]
}
个。可能吗。我在枢轴上阅读了很多,但我真的很困惑。
我的目标是获得这样的数据:
displaynames
我们在这里看到每个votes
中新的comment
数组和{{1}}数组。
我是否必须在这里以一对多的关系使用数据透视?
答案 0 :(得分:3)
你的控制器:
Entity::
with(['comments' => function($query){
$query->with('votes');
}, 'thumbs' => function($query){
$query->with('votes');
}])
->find($entity->id);
和关系:
entity has many comments
entity has many thumbs
thumb has many votes
comment has many votes
你应该告诉更多关于displayName关系的具体信息......
修改强>
Entity::
with(['comments' => function($query){
$query->with(['votes', 'displayName']);
}, 'thumbs' => function($query){
$query->with(['votes', 'displayName']);
}, 'displayName'])
->find($entity->id);
修改-2:强>
Entity::
with(['comments' => function($query){
$query->with(['votes' => function($query){
$query->with('displayName');
}, 'displayName']);
}, 'thumbs' => function($query){
$query->with(['votes' => function($query){
$query->with('displayName');
}, 'displayName']);
}, 'displayName'])
->find($entity->id);