Radical_Activity
Radical_Activity

Reputation: 2738

Laravel select specific columns with Eloquent while eager loading

I'm using Laravel 8. I have 2 tables and trying to select specific columns from both tables using Eloquent:

$ids = [1, 8, 14];
$food = Food::with(
            ['animals' => function ($query)
            {
                $query->select('id', 'name');
                $query->where('status', 1);
            }])
            ->select('id', 'type')
            ->whereIn('id', $ids)
            ->where('status', 1)
            ->get();

However, if I add a select method to the Food model, Laravel returns null for the animals table.

If I don't specify selects on the Food model, Laravel returns everything from the Food model and id, name from the animals table.

How can I select both from the Food and the Animal table simultaneously, while using Eager Loading?

Upvotes: 1

Views: 2428

Answers (3)

BGiezen
BGiezen

Reputation: 69

lagbox's suggestion actually pointed me in the direction of the solution to my issue, which was similar to the original issue. I also had a query with a select-statement and was trying to eager load a relationship. In my case the problem lay with aliasing the id that was needed to load the relationship.

So originally my code looked like this: Question::query()->select(['questions.id AS question_id', [...])->with('translations')->get(). It was actually the "AS question_id" part that led to the relationship data turning up as empty arrays. Once I deleted that alias and selected it as just 'questions.id', the relationship data could be retrieved again.

Upvotes: 0

lagbox
lagbox

Reputation: 50481

You have to make sure you are selecting the id's and any foreign keys that would be needed for the relationship from either side of that relationship. This allows Eloquent to match up parents to their children.

Upvotes: 3

szebasztian
szebasztian

Reputation: 171

Try this one, specify the table in select.

Food::with(['animals' => function ($query) {
            $query->where('status', 1);
        }])
        ->select('food.id', 'animals.type', 'food.type')
        ->whereIn('id', $ids)
        ->where('status', 1)
        ->get();

Upvotes: -1

Related Questions