首页 > 解决方案 > Laravel - 什么样的关系?

问题描述

我只是想学习 Laravel,这是我在这里的第一个问题,所以我希望我能正确描述它。

我有 3 个模型 PROFILE、CUSTOMER 和 VEHICLE(还有 USER)

用户有个人资料,每个个人资料可以有多个客户,每个客户可以有多个车辆。我想创建一个索引页面,其中登录用户及其个人资料显示所有客户的所有车辆。当我尝试这个时:

auth()->user()->profile->customers

它让我所有的客户,没关系,但我想继续做这样的事情

auth()->user()->profile->customers->vehicles

或者可能

auth()->user()->profile->vehicles

我认为“hasManyThrough”会帮助我,但不会

我想为所有客户获取所有车辆的清单。但它不起作用。

非常感谢您的帮助

用户模型

public function profile(){
    return $this->hasOne('App\Profile');
}

轮廓模型

public function user(){
    return $this->belongsTo('App\User');
}

public function customers(){
    return $this->hasMany('App\Customer');

}

public function vehicles(){
    return $this->hasManyThrough('App\Vehicle', 'App\Customer'); //this is probably wrong
}

客户模式

public function profile(){
    return $this->belongsTo('App\Profile');
}

public function vehicles() {
    return $this->hasMany('App\Vehicle');
}

public function orders() {
    return $this->hasMany('App\Order');
}

车型

public function customer(){
    return $this->belongsTo('App\Customer');
}

PROFILE 表有 user_id,CUSTOMER 表有 profile_id,VEHICLES 表有 customer_id

标签: phplaravelrelationship

解决方案


推荐阅读