Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel LeftJoin where

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"

|id|company_id|worker_id |
--------------------------
|1|       2    |  61     |
|3|       3    |  66     |
|4|       2    |  69     |
--------------------------

Second tables name "workers"

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

And I whana get table like this.

|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    |

where is my model function

public static  function CvSearch($interested_field, $location)
{

    $match = "MATCH( `interested_fields`) AGAINST (?)";

    $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')
                ->where('company_saved_cv.company_id', '=', Session::get('company_id') );


        })
        ->where('workers.location', '=', $location)
        ->whereRaw($match, array($interested_field))
        ->orderBy('workers.created_at')
        ->paginate(10);
    return $query;
}

If I comment this line:->where('company_saved_cv.company_id', '=', Session::get('company_id') ); It is working, but I need get only rows from workers table where company_id = 2 (in my example);

Session::get('company_id') = 2 

I will check it by logging it in laravel.log file.

I fink it is problem with where('company_saved_cv.company_id', '=', Session::get('company_id') ); request, but I can't figure it out, maybe some one can help me?

like image 337
lggg3 Avatar asked Nov 03 '14 09:11

lggg3


1 Answers

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."'"));


        })
like image 88
lggg3 Avatar answered Oct 13 '22 14:10

lggg3