【问题标题】:Laravel Eloquent ORM filtering with relationshipLaravel Eloquent ORM 过滤与关系
【发布时间】:2015-04-04 00:10:41
【问题描述】:

我正在制作过滤器,但有一个我无法解决的问题。过滤器使用关系,它是完美的。但是,当我对表中不存在的属性进行过滤时,它不起作用。因为问题太复杂我给你一个示例代码:

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

【问题讨论】:

  • 不应该是where('district_id', '=', Input::get('district'))吗?
  • 是的,这又是我的错误,但错误相同:(
  • CityDistrict 有什么关系?
  • 我用表格结构编辑问题
  • 根本没有关系。你怎么知道什么属于哪个区。你可能在某个地方需要district_id

标签: php sql laravel eloquent


【解决方案1】:

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

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

(假设您的Citymodel 中有municipality() 关系)

【讨论】:

  • 我收到了这个错误Call to undefined method Illuminate\Database\Query\Builder::city.municipality()
  • 最近才启用whereHas 中的嵌套关​​系支持。使用 composer update 更新 Laravel。
  • 此功能仅在@dev 上提供,因为 L4 已经一个多月没有更新新版本了。所以你需要使用例如。 4.2*@dev for laravel/framework 在你的 composer.json 中
  • 我安装了@dev,改成Call to undefined method Illuminate\Database\Query\Builder::municipality()
  • @mertindervish 听起来您的City 没有定义municipality 关系。
猜你喜欢
  • 1970-01-01
  • 2020-03-25
  • 2014-12-27
  • 2016-10-15
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 2015-04-16
相关资源
最近更新 更多