简体   繁体   中英

How to fetch record from three table in laravel eloquent

I have four tables

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 have unique rows.
  • lastsubcategoryselectedbycompanies is a mapping of jobposts and lastsubcategorymasters .

Now assume some user is logged in with their credentials (EX: take user_id 1 in jobposts ). Now I need to show LastSubCategoryName in a comma separated list from the lastsubcategorymasters table, grouped by the jobposts , lastsubcategoryselectedbycompanies and lastsubcategorymasters tables.

allpostedjob.blade.php is:

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

cotroller is:

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 model is:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

It is working proper.

But I also need to show LastSubCategoryName grouped by the tables jobposts , lastsubcategoryselectedbycompanies and lastsubcategorymasters .

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

It is not working. How can I fetch my result?

I am not very skilled at applying complex queries with eloquent, I prefer to use DB query builder with the join method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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