ryanmortier's avatar

Eager loading specific columns on relationship not working when specifying columns on parent model

I have the following simplified query:

$this->orders = Order::with(['category:id,name', 'assignee:id,name'])
    ->select(['id', 'title', 'status', 'priority'])
    ->get();

This query results in having all of the relationships null for all orders. However, if I remove the select from the parent model:

$this->orders = Order::with(['category:id,name', 'assignee:id,name'])
    ->get();

Then it works, I get the specified columns on the relationships but unfortunately I also get all columns on the orders table. How can I specify columns for both the orders table and the relationships?

0 likes
2 replies
LaryAI's avatar
Level 58

To specify columns for both the orders table and the relationships, you can use the select method on the relationship itself. Here's an example of how you can modify your query to achieve this:

$this->orders = Order::with(['category' => function ($query) {
        $query->select('id', 'name');
    }, 'assignee' => function ($query) {
        $query->select('id', 'name');
    }])
    ->select(['id', 'title', 'status', 'priority'])
    ->get();

In this example, we are using the with method to eager load the category and assignee relationships. Inside the closure for each relationship, we use the select method to specify the columns we want to retrieve from the related table.

Note that you need to use the array syntax (['category' => function ($query) {...}]) when eager loading relationships with specific columns.

This modified query will retrieve only the specified columns for both the orders table and the related tables.

ryanmortier's avatar

Fixed it.

Turns out I forgot the foreign keys on the select.

->select(['id', 'title', 'status', 'priority', 'category_id', 'assignee_user_id'])

Please or to participate in this conversation.