Home » Php » php – Laravel 5.6 Eager Loading specific column returns nothing

php – Laravel 5.6 Eager Loading specific column returns nothing

Posted by: admin July 12, 2020 Leave a comment

Questions:

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"
        }
   ]
}
How to&Answers:

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

Answer:

I got the same problem but i solved it by the following way:

// Change this in model 
public function formats()
{
    return $this->hasMany(ProductFormat::class)->select(['id', 'upc']); 
}

// No need to join here. 
$data = Product::all();
foreach ($data as $key => $value) {
    echo "<pre>";
    print_r($value->formats);
}

By this you will get the required format.

Answer:

I ran into this problem so i had to write my query this way. You will need to retrieve the ID of the foreign Key unless you get a null value from the relationship

Transaction::with([
    'client' => function($query){
        $query->select('id', 'first_name');
    }
])->get();