【发布时间】:2021-07-11 14:09:06
【问题描述】:
您好,我正在尝试通过 hasOneThrough 关系获取车辆模型,但我的属性失败了,我做错了什么?
表格
| vehicles |
|---|
| id |
| color |
| brand_id |
| brands |
|---|
| id |
| name |
| vehicle_models |
|---|
| id |
| name |
| brand_id |
型号
客户
public function Vehicles(){
return $this->belongstoMany(Vehicle::class);
}
车辆
public function brand()
{
return $this->BelongsTo(Brand::class);
}
public function client(){
return $this->belongstoMany(Client::class);
}
public function vehiclemodel(){
return $this->hasOneThrough(VehicleModel::class, Brand::class,'brand_id','id','id','brand_id');
}
品牌
public function vehicles()
{
return $this->hasMany(Vehicle::class);
}
车辆模型
public function brand()
{
return $this->hasMany(Brand::class);
}
查询
$Client = Client::find($id);
foreach($Client->vehicles->vehiclemodel as $c){
echo $c->name;
}
【问题讨论】:
-
这个问题以前有人问过;请在发布之前搜索您的错误。在您的情况下,
$client->vehicles是Collection,因此您无法访问->vehiclemodel,除非您循环。foreach($client->vehicles as $vehicle){ echo $vehicle->vehiclemodel; }(或类似)
标签: laravel eloquent laravel-collection