我只想使用Eagle加载从products_type
表中获得file_name
和id
列,但Laravel急切地加载了一个空结果。但是,当使用belongsTo(请参阅下面的类别关系)时,这种技术是有效的。
我哪里错了?或者,最不可能的是,hasMany关系有问题吗?
控制器
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
}
以下是中的一些关系
产品型号
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
型号
public function products(){
return $this->belongsTo('Products','product_id');
}
tldr您总是需要选择关系中涉及的foreign key
/primary key
。
您的belongsTo
有效,因为:
// Child belongsTo Parent
// so, when you select parent.id,parent.name, Eloquent can match fk-pk:
$child->parent_id == $parent->id;
hasMany
不起作用,因为:
// 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
所以,假设您只为belongsTo
选择parent.name
,那么这将不起作用。
话虽如此,您进行了查询,提取了正确的行,但不允许Eloquent完成其工作。