对Laravel中父级列的雄辩查询

时间:2016-04-16 19:08:32

标签: php laravel-5.2

我可以在我的模型单元的某些列中搜索。

$units = Unit::where('name', 'LIKE', '%' . $query . '%')        
            ->orWhere('address', 'LIKE', '%' . $query . '%')->paginate(15);

单位属于名为Property的模型:

public function property()
    {
        return $this->belongsTo('App\Property');
    }

我如何搜索属性的属性?

我试过了:

$units = Unit::where('name', 'LIKE', '%' . $query . '%')        
            ->orWhere('address', 'LIKE', '%' . $query . '%')->paginate(15);
            ->orWhere('property.name', 'LIKE', '%' . $query . '%')->paginate(15);

但我收到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'property.name' in 'where clause' 

1 个答案:

答案 0 :(得分:3)

试试这个: 我假设您的表格为:unitsproperties,其主键均为id,外键为单位:property_id

$units = Unit::select('units.*')
        ->where('units.name', 'LIKE', '%' . $query . '%')        
        ->orWhere('units.address', 'LIKE', '%' . $query . '%')
        ->join('properties','properties.id','=','units.property_id')
        ->orWhere('properties.name', 'LIKE', '%' . $query . '%')->paginate(15);