【问题标题】:Property [vehiclemodel] does not exist on this collection instance. in hasOneThrough relationship此集合实例上不存在属性 [vehiclemodel]。在 hasOneThrough 关系中
【发布时间】: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;
        }

【问题讨论】:

标签: laravel eloquent laravel-collection


【解决方案1】:

Laravel Eloquent 关系顾名思义是“雄辩的”。这意味着函数基本上描述了代码的结构。

拥有东西,意味着你拥有的东西知道谁是它的主人,因此额头上写着你的id的东西是属于你的,而你有一个(hasOne)东西或有很多(hasMany)个东西。它们之间的区别在于 hasOne 先取,而 hasMany 取所有并将它们放入集合中。

归属的工作方式相同,手机知道它属于一个人,因为那个人的名字写在屏幕顶部或其他任何地方。

在您的情况下,品牌有一个(或有很多)车辆,以及车辆型号。

在您描述的这个特定场景中,车辆和车辆模型都属于品牌,但是因为它们都“属于”它们彼此之间没有直接关系。您从一个到另一个的最简单方法是调用 $vehicle->brand->vehicle_model 或反过来。

您也应该能够通过使用来做到这一点(尽管不推荐,因为它不适合那种关系)

$this->hasOneThrough(VehicleModel::class, Brand::class, 'id','id','brand_id','brand_id') 

如果我没记错的话。

belongsToMany 发生在您拥有多个父母的 id 基数时,通常会附带一个中间表,而这里您没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2020-11-12
    • 2019-03-23
    • 2020-07-11
    • 2017-05-12
    相关资源
    最近更新 更多