mertindervish
mertindervish

Reputation: 301

Laravel Eloquent ORM filtering with appended attribute

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)

Upvotes: 0

Views: 3005

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

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);

Upvotes: 4

Related Questions