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

时间:2018-09-21 15:07:24

标签: php laravel eloquent

我正在与laravel合作,并且基本上通过以下方式获得了这3个相关模型:人员模型(Person.php),任务模型(Task.php)和发布模型(Post.php)。

Person.php

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

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

Task.php

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

Post.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"
    }
 ]

1 个答案:

答案 0 :(得分:0)

$a = DB:table('posts')->get();
$b = DB:table('tasks')->get();
$c = array_merge($a,$b);

请参阅文档: this