[英]Laravel: find if a pivot table record exists
I have two models which are joined by a pivot table, User
and Task
.我有两个模型,它们由数据透视表、
User
和Task
。
I have a user_id
and a task_id
.我有一个
user_id
和一个task_id
。
What is the neatest way to check whether a record exists for this combination of user and task?检查用户和任务的这种组合是否存在记录的最简洁方法是什么?
You have a couple options depending on your situation.根据您的情况,您有几种选择。
If you already have a User
instance and you want to see if it has a task with a certain id, you can do:如果您已经有一个
User
实例并且您想查看它是否有一个具有特定 id 的任务,您可以执行以下操作:
$user = User::find(1);
$hasTask = $user->tasks()->where('id', $taskId)->exists();
You can reverse this if you have the Task
instance and want to check for a user:如果您有
Task
实例并想要检查用户,则可以反转此操作:
$task = Task::find(1);
$hasUser = $task->users()->where('id', $userId)->exists();
If you just have the ids, without an instance of each, you could do the following:如果您只有 id,而没有每个实例,则可以执行以下操作:
$hasPivot = User::where('id', $userId)->whereHas('tasks', function ($q) use ($taskId) {
$q->where('id', $taskId);
})
->exists();
你可能会搜索这个吗?
$users = User::has('task')->get();
You can also try this, this is working in Laravel 5.7你也可以试试这个,这在 Laravel 5.7 中有效
$user = User::find(1);
$hasTask = $user->tasks->contains($taskId);
But the better way will be但更好的方法是
$hasTask = $user->tasks()->where('tasks.id', $taskId)->exists();
对我来说最容易阅读的是:
$user->tasks()->exists();
You can use the code below:您可以使用以下代码:
$user = User::find(1);
$hasTask = $user->tasks()->where('task_id', $taskId)->exists();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.