Laravel Eloquent ORM过滤附加属性

时间:2015-02-03 21:29:53

标签: php sql laravel eloquent

我正在制作一个过滤器,我需要追加模型一个不存在的属性,然后用它来过滤表格。我尝试使用where(),但问题是它没有找到附加的属性。这是一个示例代码:

<?php

class School extends Eloquent {

    protected $table = 'schools';
    protected $appends = array('municipality_id');

    public function getMunicipalityIdAttribute()
    {
        return City::find($this->city_id)->municipality_id;
    }

    public function listSchoolsEndUser()
    {
        $schools_data = new School;

        if ( Input::has('municipality') ) {
            $schools_data = $schools_data->where('municipality_id', '=', Input::get('municipality'));
        }

        $schools_data = $schools_data->paginate(12);

        return $schools_data;
    }
}

错误是:

SQLSTATE[42S22]: Column not found: 1054 Unknown column municipality_id' in 'where clause' (SQL: select count(*) as aggregate from `schools` where (`specialties` like %"5"%) and `municipality_id` = 6)

1 个答案:

答案 0 :(得分:3)

您的数据库中不存在自定义属性,因此您无法在SQL查询中使用它们。

为什么不直接为City定义关系并使用它进行过滤?

public function city(){
   return $this->belongsTo('City');
}

然后:

$schools_data = new School;

    if ( Input::has('municipality') ) {
        $schools_data->whereHas('city', function($q){
            $q->where('municipality_id', '=', Input::get('municipality'));
        });
    }

    $schools_data = $schools_data->paginate(12);