18

I'm trying to select all results from one table and merge with another table when user ID's match.

I have three tables: runs, users and a run_user pivot table. I want to select all results from 'runs' and additional columns in the pivot table (which are 'completed', 'sticky', 'last_tested' and 'difficulty'), but only pull data from run_user for the current user.

In raw SQL I've managed to do this via a LEFT JOIN with an AND statement:

SELECT
runs.startpoint,
runs.startpostcode,
runs.endpoint,
runs.endpostcode,
run_user.completed,
run_user.sticky,
run_user.last_tested,
run_user.difficulty
FROM runs
LEFT JOIN run_user ON run_user.run_id=runs.id AND run_user.user_id = '2'

Any suggestions how to do this via the Query Builder? I can do the LEFT JOIN in Laravel 4 but can't figure out how to combine this with an AND statement as well.

Any help is appreciated.

Thanks!

6 Answers 6

34

As you requested, this is how you would do your query with the query builder:

DB::table('runs')
        ->leftJoin('run_user', function($join)
        {
            $join->on('run_user.run_id', '=', 'runs.id')
            ->on('run_user.user_id', '=', '2');
        })
        ->get();

But that JOIN statement looks a bit weird, you probably want to turn that into a normal WHERE (unless you have a very specific reason to filter directly in the JOIN clause).

DB::table('runs')->join('run_user', 'run_user.run_id', '=', 'runs.id')->where('run_user.user_id', '=', '2')->get();

Docs: http://laravel.com/docs/queries#joins

5
  • Thanks, it looks as though the 'andOn' condition doesn't work with version 4 (laravel.com/api/class-Illuminate.Database.Query.JoinClause.html) Jul 1, 2013 at 19:42
  • You are right, sorry. I edited my answer, you can do ->on()->on() to do ANDs on a JOIN. Jul 1, 2013 at 21:45
  • 6
    Creating a join a field and then a where is not the same thing as 2 conditions on join.
    – Mihai P.
    Dec 18, 2013 at 0:18
  • in case if you want to pass dynamic value in place 'run_user.user_id', '=', '2' it is giving error. for example if I try 'run_user.user_id', '=', $id it gives undefined variable $id.
    – Manojkumar
    Dec 30, 2013 at 5:45
  • 1
    That's because $id is out of scope for the closure. Change function($join) { to function($join) use($id) { to inject the $id variable into the closure and then use it like you wanted run_user.user_id', '=', $id . Jan 6, 2014 at 14:17
13

In case anyone is wondering I got this working using DB::raw on one of the leftJoin parameters:

DB::table('runs')
    ->leftjoin('run_user', 'runs.id','=', 
      DB::raw('run_user.run_id AND run_user.user_id = ' . $user->id))
    ->get();

It's not as 'eloquent' as I'd like it to be but without a working 'andOn' condition this seems to be the only way if you want to add an AND to the LEFT JOIN.

If anyone can suggest a neater way I'd love to know!

Thanks

2
  • 2
    You can do it with ->leftJoin() and a closure with ->on()->on() like I showed in my answer, which is much cleaner. Also your double JOIN clause should really be a WHERE. Jul 2, 2013 at 12:37
  • 1
    I think this solution is better.
    – Sky
    Aug 9, 2016 at 9:28
5

use this

DB::table('runs')->select('runs.startpoint','runs.startpostcode','runs.endpoint','runs.endpostcode','run_user.completed','run_user.sticky','run_user.last_tested','run_user.difficulty')
    ->leftJoin('run_user', function($join)
    {
        $join->on('run_user.run_id', '=', 'runs.id')
        ->where('run_user.user_id', '2');
    })
    ->get();
1

In Laravel 4 you can do this using Eloquent query. I assume that you are aware of Eloquent relationships and know to to create models. For your query it should be

RunUser::where('user_id',$id)->leftjoin('runs','runs.id','=','run_user.run_id')->first();

Note RunUser is the model for run_user table.

2
  • Thanks for your suggestion. Unfortunately I have the same problem using the 'where' clause. This works fine for rows where the run_user table has a record for runs but doesn't get all of runs. Jul 1, 2013 at 20:21
  • try changing to Runs::where('id',$id)->leftjoin('run_user','run_user.run_id','=','runs.id')->first(); Jul 2, 2013 at 5:47
0

Provident and user Table Join and get id to all details.

   $return = DB::table(config::get('databaseconstants.TBL_USER'))
            ->leftjoin('inex_pf_details', 'inex_users.id', '=', 'inex_pf_details.pf_user_id')
            ->select('inex_pf_details.*','inex_users.*')
            ->where('inex_pf_details.id', $id)
            ->first();
    return $return;
0

Here is must work:

DB::table('runs')
        ->leftJoin('run_user', function($join) use ($user_id)
        {
            $join->on('run_user.run_id', '=', 'runs.id')
            ->where('run_user.user_id', '=', $user_id);
        })
        ->get();
1
  • 1
    Could you explain how this works or what it is supposed to do? Jun 14, 2017 at 20:51

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.