首页 > 解决方案 > 如何在laravel中的关系中设置查询?

问题描述

我有这张桌子

用户合约

在此处输入图像描述

用户

在此处输入图像描述

邀请

在此处输入图像描述

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

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

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')

标签: laraveleloquentrelationship

解决方案


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

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


推荐阅读