【问题标题】:Laravel Eloquent collection my scopesLaravel Eloquent 收集我的范围
【发布时间】:2015-02-05 17:43:29
【问题描述】:

我需要将 6 个示波器合二为一,以便更轻松地使用它们。 laravel可以吗?这是我使用它们的地方:

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

    if ( Input::has('specialties') ) {
        $schools_data = $schools_data->whereSpecialties(Input::get('specialties'));
    }

    if ( Input::has('district') ) {
        $schools_data = $schools_data->whereDistrict(Input::get('district'));
    }

    if ( Input::has('municipality') ) {
        $schools_data = $schools_data->whereMunicipality(Input::get('municipality'));
    }

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

    if ( Input::has('type') ) {
        $schools_data = $schools_data->whereType(Input::get('type'));
    }

    if ( Input::has('financing') ) {
        $schools_data = $schools_data->whereFinancing(Input::get('financing'));
    }

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

    return $schools_data;
}

我需要多次使用这些过滤器,但我认为没有理由再次重复相同的代码。

编辑:我的示例范围范围

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

    return $query->where(function($q) use ($districts)
    {
        foreach ($districts as $district)
        {
            $q->whereHas('city.municipality', function ($q) use ($district) {
                $q->where('district_id', '=', $district);
            });
        }
    });
}

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    遍历所有输入并添加应该工作的位置:

    $schools_data = School::query();
    $filters = Input::only('specialities', 'district', 'municipality', 'city', 'type', 'financing');
    
    foreach($filters as $filter => $value){
       call_user_func(array($schools_data, 'where' . studly_case($filter)), $value);
    }
    
    return $schools_data->paginate(12);
    

    【讨论】:

    • 这是因为我有更新问题中示例中的范围吗?
    • 当我使用此代码时,它的调用范围没有过滤器的值。我必须使用 if 来检查吗?
    • 不存在的输入被仅输入法覆盖。如果你可能有空字符串,你可以添加一个 if 子句。
    • 当在url中不存在这些查询时,它们都在foreach中使用并抛出错误。我想在范围内添加 if 子句。
    • 我不明白你的意思
    猜你喜欢
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多