【发布时间】: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