Mysql 使用with()时使用相关模型列的雄辩where子句-laravel 4

Mysql 使用with()时使用相关模型列的雄辩where子句-laravel 4,mysql,sql,laravel,laravel-4,eloquent,Mysql,Sql,Laravel,Laravel 4,Eloquent,我有两种型号 卡车 卡车类型 我需要查找相关的表记录,即TruckType 但是上面的查询没有解析TruckType.max_weight并抛出以下错误 SQLSTATE[42S22]:未找到列:1054 where子句中的未知列“TruckType.max_-weight”SQL:选择count*作为TruckType.max_-weight>=0的卡车的聚合,我想您误解了with的实际工作方式。它仅用于减轻查询的压力,不使表的内容可用于查询。运行第一次查询以选择所有卡车后,with只会导致自

我有两种型号

卡车

卡车类型

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

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


SQLSTATE[42S22]:未找到列:1054 where子句中的未知列“TruckType.max_-weight”SQL:选择count*作为TruckType.max_-weight>=0的卡车的聚合,我想您误解了with的实际工作方式。它仅用于减轻查询的压力,不使表的内容可用于查询。运行第一次查询以选择所有卡车后,with只会导致自动运行以下查询:

从TruckType中选择*,其中TruckType.id位于。。。 在这里,末尾的列表将包含在第一次查询中找到的所有不同的truck.trucktype_id值,然后它们将自动供您通过$truck->trucktype->{property}等使用

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

从TruckType.max_weight>=0的卡车中选择count*作为骨料 这就是抛出错误的原因

您有两个选择:

1使用连接

$trucksobj=Truck::with'TruckType'->加入'TruckType','Truck.TruckType_id','=','TruckType.id'->其中'TruckType.max_weight','>=',0; 2使用whereHas来约束你们的关系

$trucksobj=Truck::带有'TruckType'->其中有'TruckType',函数$q{ $q->其中'max_weight','>=',0; };
如果您实际上不需要了解卡车类型的任何信息,并且只想使用它来筛选卡车,那么您可以使用“TruckType”来摆脱,只保留查询的其余部分。

使用have而不是上一条语句中的where如何?我在这里没有使用聚合函数。。所以没有必要使用
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'];
}
$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);