Laravel 4:将where子句添加到连接条件

时间:2014-01-02 09:48:22

标签: php database laravel laravel-4 fluent

它在laravel docs中说可以在连接上添加where子句,但每当我使用where子句尝试使用我的代码时,我都会收到错误:Call to undefined method Illuminate\Database\Query\JoinClause::where()。任何人都知道如何在join子句中添加where子句?

Laravel网站示例:

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

我正试图实施的代码:

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();

8 个答案:

答案 0 :(得分:8)

如果您想在join上添加更多条件,请添加更多$join->on$join->orOn

如果要为第一个选择添加条件,请将其添加到连接函数外部。

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();

<强>更新
在我认为您使用的Laravel 4.0中,您不能在连接闭包中使用where,但是在Laravel 4.1及更高版本之后,您可以在连接条件之后具有where条件。我找不到Laravel 4.1的文档但 this is the #join documentation for L4.2 and above

答案 1 :(得分:5)

请检查以下答案

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

答案 2 :(得分:3)

尝试此解决方案

 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();

答案 3 :(得分:1)

您正在调用$ current_date,但是您将取消$ date

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();

我不知道这是否解决问题,试试吧;)

答案 4 :(得分:1)

您确定使用的是laravel 4.1吗?我认为你使用的是laravel 4.0而不是4.1。查看您的composer.json文件。

答案 5 :(得分:1)

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

答案 6 :(得分:0)

$users = DB::table('users')
    ->join('contacts', 'users.id', '=','contacts.user_id')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.*', 'contacts.phone', 'orders.price')->get();

https://laravel.com/docs/5.6/queries请查看此链接

答案 7 :(得分:0)

get()函数调用之前添加它

->where('contacts.effective_date', '=', $current_date);