繁体   English   中英

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

[英]Laravel 4: Adding where clause to a join condition

它在laravel 文档中说可以在连接上添加 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();

如果您想在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 join 闭包内使用where ,但是从 Laravel 4.1 及更高版本开始,您可以where join 条件之后使用where条件。 我找不到 Laravel 4.1 的文档,但这是 L4.2 及更高版本的 #join 文档

请检查以下答案

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)
             ->where('contacts.effective_date', '=', $current_date);

            })
            ->get();
$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();

你打电话给 $current_date 但你 decarle $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();

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

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

$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请查看此链接

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM