Laravel Eloquent ORM filtering with relationship

2019-08-04 02:06发布

I'm making a filter and there is a problem that I can't solve. The filter uses relationship and it's perfect. But when I make a filter of attribute that doesn't exist in the table it doesn't work. Because the question was too complicated I will give you an example code:

<?php

class School extends Eloquent {

    protected $table = 'schools';

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

    public function municipality(){
        return $this->belongsTo('Municipality');
    }

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

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

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

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

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

        return $schools_data;
    }
}

And the error is:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'district_id' in 'where clause' (SQL: select count(*) as aggregate from `schools` where (`specialties` like %"5"%) and (select count(*) from `cities` where `schools`.`city_id` = `cities`.`id` and `district_id` = 5) >= 1)

And the example table structure is:

Schools table:
|---------------|
|id|name|city_id|
|---------------|

Cities table:
|-----------------------|
|id|name|municipality_id|
|-----------------------|

Municipalities table:
|-------------------|
|id|name|district_id|
|-------------------|

Districts table:
|-------|
|id|name|
|-------|

1条回答
走好不送
2楼-- · 2019-08-04 02:39

Because district_id is two relations away you need to use the dot syntax to target nested relations:

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

(This assumes you have a municipality() relation in your Citymodel)

查看更多
登录 后发表回答