如何解决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')
作为作者属性将添加到帖子收藏中
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。