2

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?

5
  • 1
    you have to make sure to also select any foreign keys needed for the relationship Commented Oct 6, 2020 at 18:54
  • can you share animals relationship function? Commented Oct 6, 2020 at 18:57
  • @lagbox This was the problem, thank you so much for pointing it out. I left out one of the foreign keys from the select query! If you create an answer, I'll approve it! Commented Oct 6, 2020 at 20:13
  • which table has the foreign key in this scenario, btw? Commented Oct 6, 2020 at 20:17
  • @lagbox The animals table. I added it to the food table's select and it worked instantly. Commented Oct 7, 2020 at 10:53

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

-1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.