doutinghou6980 2015-02-03 21:29
浏览 370
已采纳

Laravel Eloquent ORM过滤附加属性

I'm making a filter and I need to append to model a attribute that doesn't exist and then use it for filtering table. I try with where() but the problem is that it isn't found the appended attribute. Here is an example code:

<?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;
    }
}

The error is:

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条回答 默认 最新

  • douaoli5328 2015-02-03 21:56
    关注

    Custom attributes do not exist in your DB hence you cannot use them in SQL queries.

    Why don't you just define a relationship for City and filter using that?

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

    And then:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题