首页 > 解决方案 > 使用数组的 Laravel Eloquent 关系映射

问题描述

让我们考虑一下我有一个名为的模型Post,它的表格如下:

posts:

| id | name   |
|----|--------|
| 1  | spring |
| 2  | autumn |

我有另一个模型Comment,它的表格是这样的:

comments:
    
| id | post_id | comment        |
|----|---------|----------------|
| 1  | 1       | spring is good |
| 2  | 1       | autumn is bad  |

post_id正如您所见,当我想获得带有评论的帖子时,这些模型是由 FK 连接的,我只使用:

$posts = Post::with('comments')->get();

在后台这些查询正在运行:

Q1: select * from posts
Q2: select * form comments where id IN (1,2)

最后eloquent 执行映射以返回此输出:

[
    [
        "id": 1,
        "name" : spring,
        "comments": [
        [
            "id": 1,
                "post_id ": 1,
                "comment" : spring is good,
            ],
            [
                "id": 2,
                "post_id ": 1,
                "comment" : autumn is bad,
            ],
        ]
    ],
    [
        "id": 2,
        "name" : autumn,
        "comments": []
    ]
]

现在让我们考虑一下我有一个这样的数组:

[
    [
        'id': 1,
        'post_id': 1,
        'author': tom
    ],
    [
        'id': 2,
        'post_id': 2,
        'author': jerry
    ]
]

我知道如果我有一个名为 的表authors,那么将它与帖子连接起来会很容易!但这就是重点:我想将帖子与数组合并以获得如下输出:

[
    [
        "id": 1,
        "name" : spring,
        "comments": [
            [
                "id": 1,
                "post_id ": 1,
                "comment" : spring is good,
            ],
            [
                "id": 2,
                "post_id ": 1,
                "comment" : autumn is bad,
            ],
        ],
        "authors": [
            [
                'id': 1,
                'post_id': 1,
                'author': tom
            ]
        ],
    [
        "id": 2,
        "name" : autumn,
        "comments": [],
        "authors": [
            [
                'id': 2,
                'post_id': 2,
                'author': jerry
            ]
        ],
    ]
]

我想要这样的东西:

$posts = Post::with(['comments', 'authors'])->get();

虽然没有authors桌子,也没有Author模型!看来我想使用数组作为模型!

我知道我可以在Post模型之外执行映射,但我正在寻找最干净的方法!

在这种情况下有没有办法使用雄辩的映射?

标签: laraveleloquentormmapping

解决方案


你可以尝试使用 eloquent mutators

public function getAuthorAttribute()
{
  return //your array or another eloquent
}

然后加protected $appends = ['author'];

您可以protected $casts = [];在模型属性中使用属性,例如:

protected $casts = ['author' => 'array'];
protected $appends = ['author'];
public function getAuthorAttribute()
{
  return ['your', 'array'];
}

像这样使用:Post::with('comments')作为作者属性将添加到 Post 集合中


推荐阅读