Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: Adding where clause to a join condition

It says in the laravel docs that it is possible to add where clause on a join, but whenever I try in my code using the where clause, I get the error: Call to undefined method Illuminate\Database\Query\JoinClause::where(). Anyone knows how to add where clause in a join clause?

Laravel Website Example:

DB::table('users')
->join('contacts', function($join)
{
  $join->on('users.id', '=', 'contacts.user_id')
  ->where('contacts.user_id', '>', 5);
})
->get();

Code I'm trying to implement:

DB::table('users')
->join('contacts', function($join)
{
  $current_date = date('Y-m-d');
  $join->on('users.id', '=', 'contacts.user_id')
  ->where('contacts.effective_date', '>=', $current_date);
})
->get();
like image 407
user9507 Avatar asked Jan 02 '14 09:01

user9507


People also ask

How to add multiple condition in join in Laravel?

$test = DB::table('table1 AS a') ->leftJoin('table2 AS b', 'a. field2', '=', 'b. field2') ->leftJoin('table3 AS c', function($join){ $join->on('a.

How add join in Laravel?

We first get users , which is our primary table, i.e., the table that relates to the other tables we want to join. Then, we chain users to the join() method. In this case, the first parameter or table we want to join to the users table is the contacts table. 'users.id', '=', and 'contacts.

What is ADD or condition in Laravel?

Laravel multiple where conditions - [OR]: What if you want to use OR condition in your query? You will have to use orWhere() condition for addition query. Note: First query cannot start with orWhere(). It has to be regular where().


2 Answers

Try This solution

 DB::table('users')
            ->join('contacts', function($join)
            {
                $current_date = date('Y-m-d');
                $join->on('users.id', '=', 'contacts.user_id')
                     ->where('contacts.effective_date', '>', $current_date)
             ->where('contacts.effective_date', '=', $current_date);

            })
            ->get();
like image 163
Amit Avatar answered Sep 28 '22 04:09

Amit


if you want add more condition on a join add more $join->on or $join->orOn.

if you want to add a condition to your first select, add it outside join function.

DB::table('users')
->join('contacts', function($join)
{
    $date = date('Y-m-d');
    $join->on('users.id', '=', 'contacts.user_id');
})
->where('contacts.effective_date', '>=', $date);
->get();

Updated
In Laravel 4.0 which I think you use, you can't use where inside your join closure, but since Laravel 4.1 and above you can have where conditions after your join condition. I couldn't find documentation for Laravel 4.1 but this is the #join documentation for L4.2 and above

like image 25
Pars Avatar answered Sep 28 '22 03:09

Pars