Laravel雄辩的关系映射使用数组

问题描述

让我们考虑一下我有一个名为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)

最后雄辩地执行映射以返回此输出

[
    [
        "id": 1,"name" : spring,"comments": [
        [
            "id": 1,"post_id ": 1,"comment" : spring is good,],[
                "id": 2,"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,"comments": [
            [
                "id": 1,"authors": [
            [
                'id': 1,'author': tom
            ]
        ],"comments": [],"authors": [
            [
                'id': 2,'author': jerry
            ]
        ],]
]

我想要这样的东西:

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

同时没有authors表,也没有Author模型! 看来我想使用数组作为模型!

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

在这种情况下,有什么方法可以使用雄辩的映射?

解决方法

您可以尝试使用雄辩的变异器

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')作为作者属性将添加到帖子收藏中