本文介绍了Laravel - 动态关系使用hasManyThough()和唯一合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以想到几种特别的方式来做到这一点,但我真的在寻找一种最佳做法的解决方案。

I can think of several ad-hoc ways to do this, but I'm really looking for a 'best practices' type of solution.

我有3个表涉及到

- 用户(user_id)

- 用法('user_id','provider_id','nurse_id','patient_id')

- usage_alerts('usage_id')

I have 3 tables involved
- users (user_id)
- usages ('user_id', 'provider_id', 'nurse_id', 'patient_id')
- usage_alerts ('usage_id')

我试图渴望加载警报使用 hasManyThrough()根据用户的角色。

Im trying to eager load alerts using hasManyThrough() based on a user's role.

user_id 字段是不可知的,可以应用于任何角色,因此需要进行合并和过滤。

The user_id field is agnostic, and can apply to any role, so merging and filtering needs to take place.

使用 $ this- > hasManyThrough('UsageAlert','Usage') - > get()将返回一个集合,使 - > merge()方法可用。然而,当急切的加载,返回时,我收到一个错误,因为它是一个收集对象。

Using $this->hasManyThrough('UsageAlert', 'Usage')->get() will return a collection, making the ->merge() method available. However, when eager loading, on return, i get an error since it's a collection object.

Call to undefined method Illuminate\Database\Eloquent\Collection::addEagerConstraints()

例如,这是我的当前关系(返回上面的错误)

public function alerts() 
{ 

    $alerts = $this->hasManyThrough('UsageAlert', 'Usage')->get();

    if(Sentry::getUser()->inGroup(Sentry::findGroupByName('provider')))
        $alerts->merge($this->hasManyThrough('UsageAlert', 'Usage', 'provider_id'));

    if(Sentry::getUser()->inGroup(Sentry::findGroupByName('patient')))
        $alerts->merge($this->hasManyThrough('UsageAlert', 'Usage', 'patient_id'));

    if(Sentry::getUser()->inGroup(Sentry::findGroupByName('nurse')))
        $alerts->merge($this->hasManyThrough('UsageAlert', 'Usage', 'nurse_id'));

    return $alerts;

}

任何建议?
也许太复杂一个关系?

Any suggestions?
Pperhaps too much complexity for a relationship?

推荐答案

最佳做法操纵关系,虽然官方文档缺乏。对于您的情况,您可以将 union 到主要不可知论关系中的其他查询:

Best practice manipulates the relationship, though official documentation on how lacks. For your scenario, you can union the additional queries into the primary "agnostic" relationship:

$relation = $this->hasManyThrough('UsageAlert', 'Usage');

foreach (['provider','patient','nurse'] as $group) {
    if (Sentry::getUser()->inGroup(Sentry::findGroupByName($group))) {
        $relation->getBaseQuery()->union(
            $this->
            hasManyThrough('UsageAlert', 'Usage', $group . '_id')->
            getBaseQuery()->
            select('UsageAlert.*') // limits union to common needed columns
        );
    }
}

return $relation;

此方法返回一个关系,而不是一个集合,如API用户所期望的。

This approach returns a Relation, rather than a Collection, as would be expected by API users.

这篇关于Laravel - 动态关系使用hasManyThough()和唯一合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:21