Laravel在哪里和哪里变得复杂 [英] Laravel complicated where and where

查看:70
本文介绍了Laravel在哪里和哪里变得复杂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,让我所有在html复选框数组上选择了某些特定技能的用户,这些值是数据库中技能的ID.

I have a query that gets me all users having some specific skills chosen on a html array of checkboxes, which values are the Ids in database for skills.

例如,当您具有Laravel和SQL技能时,仅当用户输入laravel和sql或其中之一时,搜索查询才应返回您,否则,不会显示您.

When you have for example Laravel and SQL skills, the search query should only return you if the user put laravel and sql or one of them, otherwise, you shouldn't be displayed.

另一种方式是:选择laravel或sql时,它将显示在用户列表中,但是如果同时选择这两个选项,则不会,尽管您仍然拥有这些技能.如果我将or替换为orWhere,那么效果很好,但即使我们输入您没有的其他技能,也会显示为相关用户.

What is happening now is the other way : When you select laravel OR sql, it will show you in users list, but if you select both, you won't, while you still have those skills. If I replace the where by orWhere, it goes fine, but will also show you as a relevant user even if we type another skill which you don't have.

这是我查询的一部分:

->when(isset($data['skills']) and $data['skills'] != null, function ($query) use ($data){
                $query->whereHas('skills', function ($subQuery) use ($data) {
                    for($i = 0; $i < count($data['skills']); $i++){
                            $subQuery->where('skills.id', $data['skills'][$i]);
                    }
                });
            })

for只是用于打开t 他从前端数据发送了一系列技能.

The for is simply for opening t he array of skills sent from the front data.

任何帮助都是有用的.谢谢

Any help would be usefull. Thank you

推荐答案

for ($i = 0; $i < count($data['skills']); $i++) {
                    $query->whereHas('skills', function ($subQuery) use ($data, $i) {
                        $subQuery->where('skills.id', $data['skills'][$i]);
                    });
                }

解决方案是简单地将whereHas放入循环中,以便每次将条件检查为新条件.

Solution was to simply put the whereHas inside the loop, so that the condition is checked as new one each time.

这篇关于Laravel在哪里和哪里变得复杂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆