php - Laravel 4 高级在哪里 - 未知专栏

标签 php mysql laravel-4 eloquent where-clause

我有一个如下所示的查询:

$items = Item::live()
  ->with('location')
  ->where('last_location_id', Input::get('last_location_id'))
  ->get();

这件事的背景是……

2 个表格:元素和汽车。

实时范围是:

public function scopeLive($query)
{
    return $query->whereHas('basic_car', function($q)
    {
        $q->whereNotNull('id')->where('sale_status', 'Live');

    });
}

这基本上会检查 cars 表中是否有与项目“car_id”字段匹配的 id,并将在 cars 表上运行一些 where 子句。

但是,我现在想检查 cars 表上的另一个字段,但使用原始查询中的 Input::get('last_location_id') 。

$items = Item::live()
  ->with('location')
  ->where('last_location_id', Input::get('last_location_id'))
  ->orWhere('ROW ON THE CARS TABLE' = Input::get('last_location_id'))
  ->get();

这不起作用,然后我尝试了:

$items = Item::live()
  ->with('location')
  ->where('last_location_id', Input::get('last_location_id'))
  ->orWhere(function($query)
  {
    $query->where('cars.Location', Input::get('last_location_id'));
  })
  ->get();

这会导致未知列“cars.Location”错误。

我的下一个测试是创建另一个范围:

public function scopeLiveTest($query)
{
    return $query->whereHas('basic_car', function($q)
    {
        $q->whereNotNull('id')->where('sale_status', 'Live')->where('Location', 1); // hardcoded ID
    });
}

并用它替换 live() 范围,但我没有受到查询本身中 orWhere 的影响,而且我也无法从输入中指定 ID。

我该怎么做?

最佳答案

您可以将参数传递给作用域,如下所示:

$items = Item::liveAtLocation(Input::get('last_location_id'))
    ->orWhere(function( $query ) { // to get the OR working
        $query->live()
              ->with('location')
              ->where('last_location_id', Input::get('last_location_id'));
    })
    ->get();

范围:

public function scopeLiveAtLocation($query, $location_id)
{
    return $query->whereHas('basic_car', function($q) use ($location_id)
    {
        $q->whereNotNull('id')->where('sale_status', 'Live')->where('Location', $location_id);
    });
}

关于php - Laravel 4 高级在哪里 - 未知专栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31030453/

相关文章:

php - 如何在sql中选择3个表

php - 为什么阿拉伯数字 (١٢٣) 在文本框中不被接受为实数?

php - 使用 Perl 进行 UI 开发的最佳方法

java - Java.sql 的 getRow() 线程安全吗?

php - 拉维尔 4.* : Get all cookies

php - 替换 notFoundHandler 设置

php - 如何使复合外键(不是复合主键)在mysql中唯一

mysql - 帮我优化这个 MySql 查询

php - 无法从对象 laravel 中检索字段值

php - 在 Laravel 4 上使用非 Laravel 包