如何从laravel雄辩的三个表中获取记录

时间:2019-08-17 13:11:34

标签: php laravel eloquent

我有四个桌子

jobposts

id | user_id | cat_id | job_title

1  |   1     |   1    | job 1
2  |   1     |   2    | job 2
3  |   2     |   3    | job 3
4  |   1     |   3    | job 4

categorymasters

id | category_name

1  |   cat1 
2  |   cat2  
3  |   cat3  
4  |   cat4  

lastsubcategoryselectedbycompanies

id | jobposts_id | lastsubcategorymasters_id

1  |   1     |   1 
2  |   1     |   2 
3  |   2     |   3  
4  |   1     |   3  

lastsubcategorymasters

id | LastSubCategoryName

1  |   lastsubcat1  
2  |   lastsubcat2  
3  |   lastsubcat3  
4  |   lastsubcat4   
  • jobposts具有唯一的行。
  • lastsubcategoryselectedbycompaniesjobpostslastsubcategorymasters的映射。

现在假定某些用户使用其凭据登录(例如:在user_id中使用jobposts1。)。现在,我需要在LastSubCategoryName表中以逗号分隔的列表中显示lastsubcategorymasters,并按jobpostslastsubcategoryselectedbycompanieslastsubcategorymasters表进行分组。

allpostedjob.blade.php是:

@foreach($jobposteddetails as $jobposteddetail)
    <tr>
     <td>{{ $jobposteddetail->job_title }}</td>
    </tr>
@endforeach

cotroller是:

public function index()
    {
        $user = Auth::user();
        $jobposteddetails = jobpost::with('categorymaster')->where('user_id', '=', $user->id)->get();
        return view('jobprovider.allpostedjob', compact('user','jobposteddetails'));
    }

jobpost.php模型是:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class jobpost extends Model
{
    function categorymaster()
     {
          return $this->belongsTo(categorymaster::class, 'cat_id');
     }
}

工作正常。

但是我还需要显示按LastSubCategoryNamejobpostslastsubcategoryselectedbycompanies表分组的lastsubcategorymasters

function lastsubcategory()
     {
          return $this->belongsTo(lastsubcategoryselectedbycompanies::class);
     }

它不起作用。如何获取结果?

1 个答案:

答案 0 :(得分:0)

我不太擅长运用复杂的查询,我更喜欢将DB查询构建器与join方法一起使用

https://laravel.com/docs/5.8/queries