通过relation获取相关数据

Get related data through relation

我正在使用 laravel 5.5.13。

我有 App\Entity,其中有许多 App\Comment 和许多 App\Thumb

现在我可以像这样轻松获取评论和拇指:

public function show(Entity $entity)
{
    return $entity->load('comments')->load('thumbs');
}

这给出了这样的数据:

{
    "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 s 通过 $comment->votes()。可能吗。我读了很多关于 pivot 的文章,但我真的很困惑。

我的目标是获取这样的数据:

{
    // 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 数组和每个 comment 中的 votes 数组。

我必须在这里使用 pivot 来建立一对多关系吗?

您的控制器:

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);

EDIT-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);