您可以在分支模型上使用 laravel 的默认Has Many Through来选择关联的警报
class Branch extends Model
{
public function alerts()
{
return $this->hasManyThrough(
'App\Models\Alert',
'App\Models\Group',
'branch_id', // Foreign key on alert table...
'group_id', // Foreign key on group table...
'id', // Local key on branch table...
'id' // Local key on group table...
);
}
}
使用这种方式,您可以将用户警报查询为
$alerts = auth()->user()->branch()->alerts()
或者您可以使用第三方包eloquent-has-many-deep,它可以轻松扩展hasManyThrough
多个相关模型
class User extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function alerts()
{
return $this->hasManyDeep(
'App\Models\Alert',
['App\Models\Branch', 'App\Models\Group'], // Intermediate models, beginning at the far parent (User).
[
'user_id', // Foreign key on the "branch" table.
'branch_id', // Foreign key on the "group" table.
'group_id' // Foreign key on the "alert" table.
],
[
'id', // Local key on the "user" table.
'id', // Local key on the "branch" table.
'id' // Local key on the "group" table.
]
);
}
}
您可以直接获取用户警报
$alerts = auth()->user()->alerts()
最后,您可以通过添加一些连接来直接拉取相关警报,从而在用户模型中定义警报关系
class User extends Model
{
public function alerts()
{
return $this->belongsTO('App\Branch', 'branch_id')
->join('branch_group', 'branches.id', '=', 'branch_group.branch_id')
->join('alerts', 'branch_group.group_id', '=', 'alerts.group_id')
->select('alerts.*');
}
}