将两个雄辩模型的数据合并到一个独立的数组中



我正在使用Laravel,我基本上有以下3个相关模型:人员模型(Person.php(,任务模型(Task.php(和帖子模型(Post.php(。

人.php

public function tasks()
{
return $this->hasMany(Task::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}

任务.php

public function person()
{
return $this->belongsTo(Person::class);
}

后.php

public function person()
{
return $this->belongsTo(Person::class);
}

这是模型的相关方式,现在我有一种方法可以恢复一个人及其任务和帖子,如下所示:

Person::with(['tasks','posts'])->findOrFail($id);

这将返回类似于以下内容的格式化数据(这是一个示例(:

{
"id": 1,
"name": "jhon",
"email": "jhon@gmail.com",
"created_at": "2018-09-14 12:07:35",
"updated_at": "2018-09-14 12:07:38",
"tasks": [
{
"id": 1,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-18 21:07:48",
"updated_at": "2018-09-19 20:47:37",
},
{
"id": 2,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-19 00:15:45",
"updated_at": "2018-09-20 15:28:58",
}
],
"posts": [
{
"id": 1,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-14 12:08:52",
"updated_at": "2018-09-14 16:21:03"
},
{
"id": 3,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-17 18:33:51",
"updated_at": "2018-09-17 18:33:51"
}
]
}

我的问题是:是否可以将任务的结果和帖子模型分离到不同的数组中,如果这可能,我应该这样做?,我想得到这样的结果:

[
{
"id": 1,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-18 21:07:48",
"updated_at": "2018-09-19 20:47:37",
},
{
"id": 2,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-19 00:15:45",
"updated_at": "2018-09-20 15:28:58",
},
{
"id": 1,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-14 12:08:52",
"updated_at": "2018-09-14 16:21:03"
},
{
"id": 3,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-17 18:33:51",
"updated_at": "2018-09-17 18:33:51"
}
]
$a = DB:table('posts')->get();
$b = DB:table('tasks')->get();
$c = array_merge($a,$b);

见文档: https://laravel.com/docs/5.7/queries

最新更新