PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 18, 2022

[FIXED] Laravel 5.6 Eager Loading specific column returns nothing

 March 18, 2022     laravel, laravel-5, php     No comments   

Issue

I have two classes, Product and ProductFormat. The relationship is defined properly, my Product hasMany ProductFormat.

public function formats()
{
    return $this->hasMany(ProductFormat::class);
}

When I'm trying to eager load the relationship with specific columns, as followed in the documentation (https://laravel.com/docs/5.6/eloquent-relationships#eager-loading), it's not working as expected.

For example, when I do the following:

Product::with('formats:id,upc')->get();

I get my products, with empty formats everywhere.

{
    id: 1,
    formats: [ ]
}

However, if I do the following:

Product::with('formats')->get();

I get the expected formats, but it has too many non needed columns.

{
    id: 1,
    formats: [
        {
            id: 1,
            upc: "101862422191",
            weight: 8.46,
            weight_unit: "kg"
        }
   ]
}

Solution

You always need foreign key/primary key, involved in the relation, to be selected. fetch product_id too in eager load and it will work

Product::with('formats:id,upc,product_id')->get();


Answered By - Usman Jdn
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing