我有以下型号:
User:
- id
- name
Location:
- id
- name
- region_id
table: user_location
- user_id
_ location_id
用户通过该表属于的ToMany位置。我还有另一个模型:
Region
- id
- name
我定义了Region具有许多位置。
有了这些关系,我如何定义用户与区域之间的关系,该区域将能够在与之关联的所有位置下找到所有用户?
<?php
class User extends Model
{
public function locations() {
return $this->belongsToMany('App\Location', 'user_location');
}
}
class Location extends Model
{
public function users() {
return $this->belongsToMany('App\User', 'user_location');
}
public function region() {
return $this->belongsTo('App\Region', 'region_id');
}
}
class Region extends Model
{
public function locations() {
return $this->hasMany('App\Location', 'region_id');
}
public function users() {
// what am I supposed to put in here?
}
}
答案 0 :(得分:1)
在这种情况下没有本机关系。
我为以下情况创建了HasManyThrough
关系:Repository on GitHub
安装后,您可以像这样使用它:
class Region extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function users() {
return $this->hasManyDeep(User::class, [Location::class, 'user_location']);
}
}