我有三个模型:Manager
,Vendor
,Banquet
这种关系是:
如何在laravel orm中获得所有关系的所有经理?</ p>
$manager = Manager::where('active',1)->get();
$vendor = $manager->vendor()->get();// -- dose not work!
$banquet = $vendor->banquet()->get();// -- dose not work!
经理型号:
class Manager extends Model{
protected $table = 'manager';
protected $primaryKey = 'id';
public function vendor(){
return $this->hasOne('ACME\Entities\Vendor','managerId','id');
}
}
这是模型
供应商模型:
class Vendor extends Model{
protected $table = 'vendor';
protected $primaryKey = 'id';
public function manager(){
return $this->belongsTo('ACME\Entities\Manager_V','id','managerId');
}
public function banquet(){
return $this->hasMany('ACME\Entities\V_Banquet' ,'vendorId' ,'id');
}
}
宴会模特:
class Banquet extends Model{
protected $table = 'banquet';
protected $primaryKey ='id';
public function vendor()
{
return $this->belongsTo('ACME\Entities\Vendor' ,'vendorId' ,'id');
}
}
答案 0 :(得分:1)
这不起作用,因为get()
给出了经理的集合。供应商有很多宴会,所以供应商模型中的banquets()
将是一个很好的约定。你应该做这样的事情:
$managers = Manager::where('active',1)->with('vendor','vendor.banquets')->get();
foreach($managers as $manager)
{
$vendor=$manager->vendor;
print_r($vendor);
foreach($vendor->banquets as $banquet)
{
print_r($banquet);
}
}
答案 1 :(得分:0)
使用和方法
PATCH
您将能够获取数据
$manager = Manager::with(['vendor','vendor.banquet'])->where('active',1)->get();
记住hasMany返回数组,hasOne返回Object并且belongsTo返回Object。