简体   繁体   English

与2个枢纽分析表资料搜寻的多对多关系

[英]Many to Many Relationship with 2 pivot table data search

Skills
-------
id  name
1   PHP
2   Laravel

Qualifications
-----------------
id  name
1   MBA
2   Graduate
3   Post Graduate

students
------------
id  name
1   John
2   Smith

 2 pivot tables

student_skills

student_id  skill_id
1           1
1           2
2           1

student_qualifications

tutor_id    qualification_id
1           2
1           2
2           2

In front-end the user can select multiple qualifications(checkboxes) and skills(checkboxes) according to the options selected we need to display the data. 在前端,用户可以根据我们需要显示数据的所选选项来选择多个资格(复选框)和技能(复选框)。

For Example: How to get students with qualification graduate and MBA and skills Laravel and PHP 例如:如何获得具有资格的毕业生和MBA以及具有Laravel和PHP技能的学生

Here is an example on how you can do it ( it might be inaccurate due to the lack of details in your question but it should give you an idea) 这是一个有关您如何执行此操作的示例(由于问题中缺少详细信息,因此可能不准确,但应该可以给您一个提示)

(i think you better use a Mutli-select box instead of check-boxes for skills & qualification) (我认为您最好使用Mutli-select而不是复选框来获取技能和资格)

Assuming you want to search student by skills & qualification And that you have the right Relations methods inside your models 假设您想按技能和资格来搜索学生,并且您的模型中具有正确的关系方法

  //Don't forget to import Students model at top of the controller
public function whatever(Request $request)
    {
    $data = Student::with('qualifications', 'skills');

     // assuming that the form will pass an array of skills names
     //if the form passes an array of ID's of skills it becomes easier

    if (!empty($request->skills)) {
        foreach ($request->skills as $skill) {
            $data->whereHas('skills', function ($query) use ($skill) {
                $query->where('id', $skill);
            })->get();
        }
    }

       // same goes for qualifications
    if (!empty($request->qualifications)) {
        foreach ($request->qualifications as $qualification) {
            $data->whereHas('qualifications', function ($query) use ($skill) {
                $query->where('id', $qualification);
            })->get();
        }
    }

    // execute the query now
   $data->get(); // or pagniate(10)
}

if you are passing an array of ID's instead of names 如果您传递的是ID而不是名称的数组

   if (!empty($request->skills)) {
            $data->whereHas('skills', function ($query) use ($skills)                   {
                $query->whereIn('id', $skills);
            })->get();
    }

same goes for qualifications. 资历也一样。

I hope you get the point here, you can Sort and stuff , this might not be the exact thing u need, but It will help you a lot if you get it. 我希望您能明白这里的意思,可以进行排序和填充,这可能并不是您真正需要的东西,但是如果您得到的话,它将对您有很大帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM