Search code examples
phplaraveleloquenteloquent-relationship

filter result of a 'subquery' in laravel 9, with eloquent


my model: a post belongs to a category.

So I want to get the category and the posts it has, with filters.

I've already tried:

$category = Category::select('id', 'name')
    ->with('post:id,title')
    ->get();

But this returns the following results:

[
  {
    "id":1,
    "name":"First Category update",
    "post":[]
  }
]

Note: When I do

$categories = Category::select('id', 'name')
    ->with('post')
    ->get();

Returns this:

[
  {
    "id":1,
    "name":"First Category update",
    "post":[
      {
        "id":1,
        "title":"New post update",
        "description":"Post text",
        "category_id":1,
        "created_at":"2022-07-13T19:30:58.000000Z",
        "updated_at":"2022-07-13T19:33:37.000000Z",
        "user_id":1
      }
    ]
  }
]

Solution

  • If you want to only select certain columns but also get relationships, you must ensure that you get all the foreign keys in the relationship. In this case, that includes posts.category_id:

    $category = Category::select('id', 'name')
        ->with('post:id,category_id,title')
        ->get();