Laravel LeftJoin where

后端 未结 3 1681
孤独总比滥情好
孤独总比滥情好 2021-01-19 09:55

I have some problems with my eloquent model, where I try to join two different tables in one

Now I have two tables like.

First tables name \"company_saved_cv

相关标签:
3条回答
  • 2021-01-19 10:21

    I solve this problem with this code

     $query = Worker::select('workers.name_and_surname', 'workers.id', 'workers.location','company_saved_cv.worker_id')
            ->leftJoin('company_saved_cv', function($leftJoin)use($company_id)
            {
                $leftJoin->on('workers.id', '=', 'company_saved_cv.worker_id');
                $leftJoin->on(DB::raw('company_saved_cv.company_id'), DB::raw('='),DB::raw("'".$company_id."'"));
    
    
            })
    
    0 讨论(0)
  • 2021-01-19 10:25

    Well when you use LEFT JOIN with where it acts as an INNER JOIN

    Use LEFT JOIN and WHERE like

    SELECT workers.name_and_surname, workers.id, workers.location,company_saved_cv.worker_id
    FROM workers LEFT JOIN company_saved_cv
    ON company_saved_cv.worker_id= workers.id
    WHERE company_saved_cv.company_id = 2
    

    OUTPUT

    |id|location|name_and_surname|worker_id|
    ---------------------------------------|
    |61|London  | John John      |  61     |
    |66|London  | John John      |  66     |
    

    Use LEFT JOIN and AND like

    SELECT workers.name_and_surname, workers.id, workers.location,company_saved_cv.worker_id
    FROM workers LEFT JOIN company_saved_cv
    ON company_saved_cv.worker_id= workers.id
    AND company_saved_cv.company_id = 2
    

    OUTPUT

    |id|location|name_and_surname|worker_id|
    ---------------------------------------|
    |61|London  | John John      |  61     |
    |62|London  | John John      | NULL    |
    |66|London  | John John      | 66      |
    |67|London  | John John      | NULL    |
    |68|London  | John john      | NULL    |
    

    New query

    $query = Worker::select('workers.name_and_surname', 'workers.id', 'workers.location','company_saved_cv.worker_id')
            ->leftJoin('company_saved_cv', function($leftJoin)
            {
                $leftJoin->on('company_saved_cv.worker_id', '=', 'workers.id')
    
                    ->on('company_saved_cv.company_id', '=', Session::get('company_id') );
    
    
            })
    
    0 讨论(0)
  • 2021-01-19 10:37

    You can easily use the Model for it. The last table, you can remove the location because you can get it with and from the model. Create easily a many-2-many relationship or something you want. Check the docs: http://laravel.com/docs/4.2/eloquent#relationships

    0 讨论(0)
提交回复
热议问题