[英]How to query through nested Laravel relationships the eloquent ORM way
I have a relationship that is almost 5 levels deep. 我的恋爱关系接近5个层次。
In my blades I use this all time without a problem. 在刀片中,我一直都在使用,没有问题。 For example:
例如:
{{ $user->team->department->region->company->name ?? ''}}
How would I go about querying all users that belong to a company? 我将如何查询属于公司的所有用户?
$users = User::where($user->team->department->region->company->id, '=', 1)->get(); ?????
Company Relationships: 公司关系:
class Company extends Model
{
public function region() {
return $this->hasMany('App\Region', 'company_id', 'id');
}
}
Region Relationships: 区域关系:
class Region extends Model
{
public function company() {
return $this->hasOne('App\Company', 'id', 'company_id');
}
public function department() {
return $this->hasMany('App\Department', 'region_id', 'id');
}
}
Department Relationships: 部门关系:
class Department extends Model
{
public function region() {
return $this->hasOne('App\Region', 'id', 'region_id');
}
public function team() {
return $this->hasMany('App\Team', 'department_id', 'id');
}
}
Team Relationships: 团队关系:
class Team extends Model
{
public function department() {
return $this->hasOne('App\Department', 'id', 'department_id');
}
public function user() {
return $this->hasMany('App\User', 'team_id', 'id');
}
}
User Relationships: 用户关系:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function team() {
return $this->hasOne('App\Team', 'id', 'team_id');
}
}
I know there must be some easy way to query through nested relationships that Laravel provides a way for or a some facility for, but I have yet to find any decent examples from Googling around. 我知道必须有一些简单的方法来查询Laravel提供的方法或某种便利的嵌套关系,但是我还没有从Googling那里找到任何不错的例子。
You can use this package for your need. 您可以根据需要使用此软件包。
https://github.com/staudenmeir/eloquent-has-many-deep https://github.com/staudenmeir/eloquent-has-many-deep
read the instructions, depth of the relationship is not limited. 阅读说明后,关系的深度不受限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.