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 |
|____|_________|
但沒有在專業的表列學校ID,當我嘗試你的代碼中的錯誤是一樣的 – mertindervish 2015-02-05 22:09:11
啊,現在我看着你表格更接近一點。將專業主鍵存儲在學校表中的陣列中是錯誤的方法。在專業表中添加'school_id'或創建一個數據透視表,如果它是多對多關係的話。 – lukasgeiter 2015-02-05 22:12:02
我將創建一個數據透視表感謝:) – mertindervish 2015-02-05 22:13:35