【问题标题】:Laravel Eloquent relationship mapping using an array使用数组的 Laravel Eloquent 关系映射
【发布时间】:2020-12-19 15:17:22
【问题描述】:

假设我有一个名为 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 连接 当我想通过 cmets 获得帖子时,我只使用:

$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 模型之外执行映射,但我正在寻找最简洁的方法!

在这种情况下有什么方法可以使用 eloquent mapping 吗?

【问题讨论】:

    标签: laravel eloquent orm mapping


    【解决方案1】:

    你可以尝试使用 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') as author 属性将添加到 Post 集合中

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 2013-04-20
      • 2015-10-16
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多