如何获得 laravel 中的关系
How to get the relation in laravel
我有三个型号:Manager
、Vendor
、Banquet
关系是:
- 经理有一个供应商
- 商贩多宴
如何在 laravel orm 中获取具有所有关系的所有经理?
$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');
}
}
使用和方法
$manager = Manager::with(['vendor','vendor.banquet'])->where('active',1)->get();
您将能够以
的形式获取数据
$banquet = $manager->vendor->banquet;
// $banquet will be array of banquet model objects
记住 hasMany return 数组,hasOne return 对象和 belongsTo return 对象。
这没有用,因为 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);
}
}
我有三个型号:Manager
、Vendor
、Banquet
关系是:
- 经理有一个供应商
- 商贩多宴
如何在 laravel orm 中获取具有所有关系的所有经理?
$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');
}
}
使用和方法
$manager = Manager::with(['vendor','vendor.banquet'])->where('active',1)->get();
您将能够以
的形式获取数据$banquet = $manager->vendor->banquet;
// $banquet will be array of banquet model objects
记住 hasMany return 数组,hasOne return 对象和 belongsTo return 对象。
这没有用,因为 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);
}
}