3
votes

I want to get just the file_name and id column from the products_type table using Eager loading but Laravel eager loads an empty result. However, when using belongsTo (see categories relationship below), this technique works.

Where have I gone wrong? Or, most unlikely, is there some problem with the hasMany relationship?


Controller

private function getProducts($category){
    return Products::with(array(
    'types'=>function($q){
            $q->first();
        },//this returns empty array
    'categories'=>function($q)use($category){
            $q->where('name','LIKE',$category);
        }))->get()->toArray();//this returns the correct result
}

These are some of the relationship in

Products model

public function types(){
    return $this->hasMany('Types','product_id')->select(array('products_type.id','products_type.file_name'));
}//doesn't work

public function categories(){
    return $this->belongsTo('Categories','category_id')->select(array('categories.id','categories.name'));
}//this works

Types model

public function products(){
    return $this->belongsTo('Products','product_id');
}
1

1 Answers

1
votes

tldr; You always need foreign key/primary key, involved in the relation, to be selected.

Your belongsTo works, because:

// Child belongsTo Parent
// so, when you select parent.id,parent.name, Eloquent can match fk-pk:
$child->parent_id == $parent->id;

And hasMany doesn't work, because:

// Parent hasMany Child
$parent->id == $child->parent_id;

// now, when you select child.id,child.name, then:
$child->parent_id; // null, therefore Eloquent can't match the keys

So, imagine you select for the belongsTo just parent.name - then this would not work as well.

That being said, you made the query, fetched correct rows, but didn't allow Eloquent to do its job.