如何解决从-多对多-到-多对多关系中检索集合的最佳方法laravel7
您可以在下图中看到我的数据库的一部分:
此设计的目标是使管理员能够动态地将alerts
发送到users
和center
过滤的field
。如果您认为这是一个不好的设计,请告诉我(请说出为什么以及如何改进我的设计)。
现在,如果我想获取用户的警报,我应该这样做:
$userAlerts = collect();
auth()->user()->branch()->first()->groups()->get()->each(function ($item,$key) use ($userAlerts) {
$item->alerts()->get()->each(function ($item,$key) use ($userAlerts) {
$userAlerts->push($item);
});
});
这段代码很荒谬,我不想这样做。
相反,我想做这样的事情:
$alerts = auth()->user()->branch()->groups()->alerts() // i want this // method 1
或
$alerts = auth()->user()->alerts() //or maybe this // method 2
是否可以在不更改数据库的情况下执行类似的操作? (方法1或2)。
解决方法
您可以在分支模型上使用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.*');
}
}
,
使用此仓库是我到目前为止找到的最好的解决方案。
https://github.com/johnnyfreeman/laravel-custom-relation。
在这种情况下:基于文档
class User extends Model {
use HasCustomRelations;
public function alerts()
{
return $this->custom(
Alert::class,// add constraints
function ($relation) {
$relation->getQuery()
->join('branch_group as bg','bg.group_id','alerts.group_id')
->join('users as u','u.branch_id','bg.branch_id')
->where('u.id',$this->id);
},// add eager constraints
function ($relation,$models) {
$relation->getQuery()->whereIn('users.id',$relation->getKeys($models));
}
);
}
}
这样,我可以使所有laravel关系方法受益。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。