通过关系获取相关数据

2024-01-14

我正在使用 laravel 5.5.13。

I have App\Entity其中有很多App\Comment的和许多App\Thumb's.

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

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"
        }
    ]
}

However,我还需要一份清单$comment->displaynames() and $thumb->displaynames()而且每个评论都有很多App\Vote是通过$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数组和一个votes每个数组中comment.

我是否必须在一对多关系中使用枢轴?


您的控制器:

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 关系的更多具体信息......

EDIT:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过关系获取相关数据 的相关文章

随机推荐