laravel - 使用数组的 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
模型之外执行映射,但我正在寻找最干净的方法!
在这种情况下有没有办法使用雄辩的映射?
解决方案
你可以尝试使用 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 集合中
推荐阅读
- python - python中的高效列表比较
- symfony - Symfony 4 + graylog + 控制台错误
- android - 如何在夜间模式下更改深色操作栏的颜色?
- android - 确定 SQLite GROUP BY 行选择
- node.js - 具有子目录的节点模块:“错误解析触发器:找不到模块 'ibm-watson'”
- javascript - 从 1 页抓取数据转到下一页等等,网站上使用的 javascript
- django - 如何在 django-bootstrap 中手动呈现表单字段
- swift - 只确定一个联系人 SpriteKit
- c# - 没有运算符与给定名称和参数类型匹配。您可能需要添加显式类型转换
- c++ - 是否 C++
标头在执行并发时使用硬件支持,或者纯粹是基于算法的解决方案