php - 检索多对多关系。拉维尔

标签 php mysql laravel laravel-5 information-retrieval

我正在尝试从多对多关系中检索数据。我有两个表:

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/

相关文章:

MySQL 模拟行数

php - 我的 PHP/MySQL 语法错误在哪里?

python - 在不复制变量的情况下重用 %s 占位符?

php - Laravel 中如何避免时间重叠

php - Laravel 5 : ErrorException in LengthAwarePaginator. php:除以零

php - 如何使用 DOM 和 XPath 从页面中抓取链接?

php - Laravel 队列不作为后台运行

javascript - Paypal 捐赠按钮额外的领域

php - iOS 推送通知反馈服务

php - 使用 DB::raw 表达式的 POINT/POLYGON 等 Laravel 模型