2015-02-05 36 views
1

我使用过滤器从URL过滤学校,我需要向用户显示这些过滤器的链接。那么,实际上我只需要向用户展示使用后它们不返回空结果的过滤器。我试着用范围和关系,我有这个错误:Laravel Eloquent为列表过滤器名称和用户链接

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'specialties.school_id' in 'where clause' (SQL: select `id`, `name` from `specialties` where ((select count(*) from `schools` where `specialties`.`school_id` = `schools`.`id` and `specialties` like %""%) >= 1)) 

对我来说,我需要过滤的特色,区,直辖市,城市学校等。这是我的例子办学模式:

<?php 

class School extends Eloquent { 
    protected $table = 'schools'; 

    public function scopeWhereSpecialties($query, $specialties) 
    { 
     if(!is_array($specialties)) 
     { 
      $specialties = [$specialties]; 
     } 

     return $query->where(function($q) use ($specialties) 
     { 
      foreach($specialties as $specialty){ 
       $q->where('specialties', 'like', '%"'.$specialty.'"%'); 
      } 
     }); 
    } 

    // I just delete other scopes to shorten the code 

    public function listSchoolsEndUser($filters) 
    { 
     $schools_data = School::query(); 

     foreach($filters as $filter => $value) 
     { 
      call_user_func(array($schools_data, 'where' . studly_case($filter)), $value); 
     } 

     return $schools_data->paginate(12); 
    } 

    public function listFilters($filters) 
    { 
     $specialties_filters = Specialty::select('id', 'name')->whereFilterAvailable($filters)->get()->toArray(); 

     return $specialties_filters; 
    } 
} 

而且还有我的例子专业模式:学校

<?php 

class Specialty extends Eloquent { 
    protected $table = 'specialties'; 

    public function scopeWhereFilterAvailable($query, $filters) 
    { 
     $specialty = $this->id; 
     return $query->where(function($q) use ($specialty, $filters) 
     { 
      $q->whereHas('school', function($q) use ($specialty, $filters) { 
       $q->where('specialties', 'like', '%"'.$specialty.'"%'); 
      }); 
     }); 
    } 

    public function school(){ 
     return $this->belongsTo('School'); 
    } 
} 

表结构similat到:

____________________________________ 
| id | name | specialties  | 
|____|_________|___________________| 
| 1 | example | ["1","2","3","4"] | 
|____|_________|___________________| 

而且表的特色结构similat到:

________________ 
| id | name | 
|____|_________| 
| 1 | example | 
|____|_________| 

回答

1

的问题是,与select('id', 'name')您限制查询,只有那些属性,因此school_id不可用。你应该包括你(和你relationshipos)所需要的所有列:

$specialties_filters = Specialty::select('id', 'name', 'school_id')->whereFilterAvailable($filters)->get()->toArray(); 

也许lists()是一种选择这里。它创建了一个数组一个属性作为键和其他的价值:

$specialties_filters = Specialty::whereFilterAvailable($filters)->lists('name', 'id'); 
+0

但没有在专业的表列学校ID,当我尝试你的代码中的错误是一样的 – mertindervish 2015-02-05 22:09:11

+1

啊,现在我看着你表格更接近一点。将专业主键存储在学校表中的阵列中是错误的方法。在专业表中添加'school_id'或创建一个数据透视表,如果它是多对多关系的话。 – lukasgeiter 2015-02-05 22:12:02

+0

我将创建一个数据透视表感谢:) – mertindervish 2015-02-05 22:13:35