繁体   English   中英

Laravel雄辩的ORM过滤与关系

[英]Laravel Eloquent ORM filtering with relationship

我正在制作过滤器,但有一个我无法解决的问题。 过滤器使用关系并且非常完美。 但是,当我对表中不存在的属性进行过滤时,它将不起作用。 由于问题太复杂了,我将为您提供示例代码:

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

错误是:

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)

表格结构示例为:

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

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

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

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

因为district_id是两个关系,所以您需要使用点语法来定位嵌套关系:

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

(这假定您在“ City模型中有一个municipality()关系)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM