Laravel Eloquent ORM 过滤附加属性

Laravel Eloquent ORM filtering with appended attribute

我正在制作一个过滤器,我需要将一个不存在的属性附加到模型中,然后将其用于过滤 table。我尝试使用 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)

您的数据库中不存在自定义属性,因此您不能在 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);