laravel - 如何在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')
解决方案
public function nonAcceptedContracts()
{
return $this->belongsToMany(UserContract::class, 'invite', 'email', 'usercontract', 'email')->where('status', 'pending');
}
该关系使用我的“邀请”表作为枢轴,使用“电子邮件”和“用户合同”具有键并使用“用户”表的“电子邮件”过滤结果。
推荐阅读
- ios - 如何禁用默认的删除滑动操作并改为显示我的自定义滑动操作?
- apache-spark - PySpark 余弦相似度变压器
- python - Tkinter pack method confusion
- android - 将视图对齐到旋转的 TextView 的顶部
- http - Http加载标志真假的区别
- python - Django-tables 分页 per_page 未按预期工作
- php - 如何像在 python 中一样在 PHP 中执行校验和?
- python - 如何解决 Fenics 示例 ft06_elasticity.py 中未定义名称“nabla_div”错误?
- cluster-computing - pcs 在同时启动两台机器时在主节点中启动它们之前不会停止伙伴节点中的故障转移资源
- excel - 我能否以编程方式启用和禁用存储在 SharePoint 中并链接到 ms-access 的 xlsx 文件的 ms-excel 文件共享/共同创作?