php - Laravel Eloquent ORM filtering with appended attribute
Get the solution ↓↓↓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)
Answer
Solution:
Custom attributes do not exist in your DB hence you cannot use them in SQL queries.
Why don't you just define a relationship forCity
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);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot set properties of undefined (setting '_dt_cellindex')
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.