Laravel:查找数据透视表记录是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35285902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: find if a pivot table record exists
提问by datavoredan
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?
检查用户和任务的这种组合是否存在记录的最简洁方法是什么?
回答by patricus
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();
回答by Yurich
may be you search this?
你可能在搜索这个吗?
$users = User::has('task')->get();
回答by Prafulla Kumar Sahu
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 using whereHas.
但更好的方法是使用 whereHas。
$hasTask = $user->tasks()->where('tasks.id', $taskId)->exists();
回答by Marcus Christiansen
Easiest to read for me is:
对我来说最容易阅读的是:
$user->tasks()->exists();
回答by spencerfeng
You can use the code below:
您可以使用以下代码:
$user = User::find(1);
$hasTask = $user->tasks()->where('task_id', $taskId)->exists();