L
L
Lesnoyyy2020-05-28 14:59:22
Laravel
Lesnoyyy, 2020-05-28 14:59:22

How to merge table query results using Laravel Eloquent?

Good day!
Please tell me about laravel Eloquent.
By executing the following code:

$cat = Category::with('posts:id,title','pages:id,title')->findOrFail($id);
return $cat;

I get the following result:
{
  "id": 1,
  "name": "Категория 1",
  "slug": "cat1",
  "parent_id": 0,
  "posts": [
    {
      "id": 1,
      "title": "Запись №1",
      "pivot": {
        "category_id": 1,
        "categoriable_id": 1,
        "categoriable_type": "App\\Post"
      }
    }
  ],
  "pages": [
    {
      "id": 1,
      "title": "Страница №1",
      "pivot": {
        "category_id": 1,
        "categoriable_id": 1,
        "categoriable_type": "App\\Page"
      }
    }
  ]
}

The question is: how to combine the posts and pages arrays to get something like this:
{
  "id": 1,
  "name": "Категория 1",
  "slug": "cat1",
  "parent_id": 0,
  "posts_and_pages": [
    {
      "id": 1,
      "title": "Запись №1",
      "pivot": {
        "category_id": 1,
        "categoriable_id": 1,
        "categoriable_type": "App\\Post"
      }
    },
    {
      "id": 1,
      "title": "Страница №1",
      "pivot": {
        "category_id": 1,
        "categoriable_id": 1,
        "categoriable_type": "App\\Page"
      }
    }
  ]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Rodichev, 2020-05-29
@Lesnoyyy

concat what you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question