【问题标题】:How to set the query in a relationship in laravel?如何在laravel中的关系中设置查询?
【发布时间】:2021-02-17 08:23:27
【问题描述】:

我有这张桌子

用户合约

用户

邀请

邀请包含参与合同的邀请,并通过电子邮件发送。我想使用电子邮件作为 id 来获取用户被邀请参与的所有合同。 而且我需要将其作为我的用户模型的关系,所以我可以使用登录的用户电子邮件作为过滤器。

这是我定义的关系,但使用用户的 id 来匹配邀请表上的foreing_key(用户合同)。我不太明白为什么。

public function nonAcceptedContracts()
{
        return $this->belongsToMany(UserContract::class, 'invite', 'email', 'usercontract');
}

我需要它作为一种关系,因为我想在我的存储库中调用它,就像这样。

public function showRelated(User $user)
    {
        $parentUser = $user->parentUser;
        $usercontract = UserContract
            ::with(['topics', 'contracttax', 'contractproperty', 'persons', 'contractwarranty', 'contractencumbrance', 'users', 'contracts', 'tags'])
            ->whereHas('users', function ($query) use ($user, $parentUser) {
                $user->loadMissing('nonAcceptedContracts');
                dd($user->nonAcceptedContracts);
                $query->where('id', $user->getAuthIdentifier());
                if ($parentUser) {
                    $query->orWhere('parent', $parentUser->id);
                }
                if ($user->siblingUsers()->count() > 0) { // get contracts of the sibling-users of the user
                    $query->orWhereIn('id', $user->siblingUsers()->pluck('id'));
                }
                if ($user->subUsers->count() > 0) { // get contracts of the users sub-users
                    $query->orWhereIn('id', $user->subUsers->pluck('id'));
                }
                return $query;
            })->orderBy('created_at', 'desc')->get();
    }

我想我的问题是如何设置关系以获取该用户(对象)的用户合同,使用他的电子邮件作为获取邀请表上的用户合同 ID(用户合同)的密钥。

SELECT * FROM `usercontract` WHERE usercontract.id IN (SELECT invite.id FROM invite WHERE `invite`.`email` = 'someemail@gmail.com')

【问题讨论】:

  • $this->belongsToMany(UserContract::class, 'invite', 'email', 'usercontract');这似乎奏效了。 sql语句看起来不错。除了那个“?”它应该是登录用户的电子邮件。 “从usercontract 内部连接invite 中选择* usercontract.id = invite.usercontract 其中invite.email = ? 和usercontract.@9876543339 为空/跨度>

标签: laravel eloquent relationship


【解决方案1】:
public function nonAcceptedContracts()
{
    return $this->belongsToMany(UserContract::class, 'invite', 'email', 'usercontract', 'email')->where('status', 'pending');
}

该关系使用我的“邀请”表作为枢轴,使用“电子邮件”和“用户合同”具有键并使用“用户”表的“电子邮件”过滤结果。

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2017-06-25
    • 2021-08-30
    • 2020-11-02
    • 2013-03-05
    相关资源
    最近更新 更多