我试图从多对多的关系中检索数据。我有两个表:
公司:[cid,名称,来源]
vehicle_types:[id,type]
他们的数据透视表:companies_vehicle_types:companies_id,vehicle_types_id关系定义:公司:
class companies extends Model
{
//
protected $fillable = ['name','origin'];
protected $primaryKey = 'cid';
public function vehicles(){
return $this->hasOne('App\vehicles');
}
public function vehicle_types(){
return $this->belongsToMany('App\vehicle_types', 'companies_vehicle_types', 'companies_id', 'vehicle_types_id');
}
}
在vehicle_types中
class vehicle_types extends Model
{
//
protected $fillable = ['type'];
public function vehicles(){
return $this->belongsTo('App\vehicles');
}
public function companies(){
return $this->belongsToMany('App\companies','companies_vehicle_types','vehicle_types_id','companies_id')->withTimestamps();
}
}
我想检索vehicle_types =特定类型的公司。我怎样才能做到这一点?我尝试在我的控制器中执行以下操作:
$vehicle_types=vehicle_types::where('type','Bike')->get();
foreach ($vehicle_types as $vehicle_type) {
# code...
foreach ($vehicle_type->companies as $company) {
$brand[]=$company->pivot->name;
}
}
return $brand;
但它似乎并没有起作用。 $ vehicle_types工作正常并且返回值。 $ brand没有返回任何价值。