【问题标题】:Eloquent where clause to use related model's column when using with() -laravel 4雄辩的 where 子句在使用 with() -laravel 4 时使用相关模型的列
【发布时间】:2014-10-15 23:51:18
【问题描述】:

我有 2 个模型

卡车

class Truck extends \Eloquent {
    // Add your validation rules here
    public static $rules = [
        'trucktype_id' => 'required',
        'weight'=> 'required',
        'truck_no'=> 'required'

    ];

    // Don't forget to fill this array
    protected $fillable = ['trucktype_id','weight','picture_path','remarks','truck_no'];

    public function TruckType(){
        return $this->belongsTo('TruckType','trucktype_id');
    }
}

卡车类型

class Trucktype extends \Eloquent {
    // Add your validation rules here
    public static $rules = array(
                    'type'         => 'required|unique:trucktypes,type',
                    'max_weight'   => 'required'
                );

    // Don't forget to fill this array
    protected $fillable = ['type','max_weight'];
}

我需要查找相关的表记录,即TruckType

$trucksobj = Truck::with('TruckType');
if($truck_no!="")
    $trucksobj->where("truck_no",'=',$truck_no);
if($start_date!="" && $end_date!="")
    $trucksobj->whereBetween('created_at', array($start_date, $end_date));
if($truck_type!="")
    $trucksobj->where("trucktype_id",'=',$truck_type);
if($overweight=="on")
    $trucksobj->where('TruckType.max_weight', '>=', 0);

但是上面的查询没有解析TruckType.max_weight并抛出以下错误

SQLSTATE[42S22]:未找到列:1054 'where 子句'中的未知列'TruckType.max_weight'(SQL:从trucks 中选择计数(*)作为聚合,其中TruckType.max_weight >= 0)

【问题讨论】:

  • 在最后一个语句中使用having而不是where怎么样?
  • 我没有在这里使用聚合函数..所以没有使用的意义

标签: mysql sql laravel laravel-4 eloquent


【解决方案1】:

我认为您误解了 with() 的实际工作原理。它仅用于缓解N+1 query problem,并且不会使表的内容可供查询。在您运行第一个查询以选择所有卡车后,with() 只会导致自动运行以下查询:

select * from TruckType where TruckType.id in (...)

最后的列表将包含您在第一个查询中找到的所有不同的 truck.trucktype_id 值,然后它们将自动供您通过 $truck->TruckType->{property} 等使用。

现在,如果您真正查看为您生成的查询,您可以清楚地看到任何地方都没有引用 TruckType 表:

select count(*) as aggregate from trucks where TruckType.max_weight >= 0

这就是引发错误的原因。


你有两个选择:

(1) 使用连接

$trucksobj = Truck::with('TruckType')->join('TruckType', 'truck.trucktype_id', '=', 'TruckType.id')->where('TruckType.max_weight', '>=', 0);

(2) 使用whereHas() 限制您的关系

$trucksobj = Truck::with('TruckType')->whereHas('TruckType', function($q) {
  $q->where('max_weight', '>=', 0);
});

如果您实际上不需要了解卡车类型的任何信息,而只想用它来筛选卡车,那么您可以去掉 with('TruckType') 并保留其余的查询。

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2017-11-05
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 2013-06-04
    • 2018-05-19
    • 2021-02-13
    相关资源
    最近更新 更多