从多对多关系中检索。 Laravel

Retrieve from many to many relationship. Laravel

我正在尝试从多对多检索数据 relationship.I 有两个 tables :

companies: [cid,name,origin]

vehicle_types: [id, type]

他们的支点table:companies_vehicle_types: companies_id,vehicle_types_id 关系定义: 在公司中:

public function vehicle_types(){

    return $this->belongsToMany('App\vehicle_types');
}

在vehicle_types

public function companies(){

    return $this->belongsToMany('App\companies')->withTimestamps();
}

我想检索 vehicle_types = 特定类型的公司。我怎样才能做到这一点? 我尝试在我的控制器中执行以下操作:

$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
}

同样,我没有在数据透视表 table 中看到 name 字段以使该行起作用:$company[]=$company->pivot->name;