我正在尝试从多对多关系中检索数据。我有两个表:
companies: [cid,name,origin]
vehicle_types: [id, type]
他们的数据透视表:companies_vehicle_types:company_id,vehicle_types_id
关系定义:
在公司中:
public function vehicle_types(){
return $this->belongsToMany('App\vehicle_types');
}
在车辆类型中
public function companies(){
return $this->belongsToMany('App\companies')->withTimestamps();
}
我想检索车辆类型 = 特定类型的公司。我怎样才能做到这一点? 我尝试在 Controller 中执行以下操作:
$vehicle_types=vehicle_types::all()->whereLoose('type','Bike');
foreach ($vehicle_types->companies as $vehicle_types) {
$company[]=$vehicle_types->pivot->name;
}
return $company;
但似乎不起作用。它抛出 Undefined property: Illuminate\Database\Eloquent\Collection::$companies
最佳答案
如果您不遵循 Laravel 的约定,请覆盖关系中的第二个、第三个和第四个参数。请参阅文档 Many to Many Relation
Second argument determines the table name of the relationship's joining table. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
public function vehicle_types(){
return $this->belongsToMany('App\vehicle_types', 'companies_vehicle_types', 'companies_id', 'vehicle_types_id');
}
此外,一个 $vehicle_type 可以有许多公司,因此:
$vehicle_types=vehicle_types::all()->whereLoose('type','Bike');
foreach ($vehicle_types as $vehicle_type) {
foreach($vehicle_type->companies as $company)
{
$company[]=$company->pivot->name;
}
endforeach
}
同样,我在数据透视表中没有看到 name
字段,此行无法正常工作:$company[]=$company->pivot->name;
关于php - 检索多对多关系。拉维尔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41788952/