【问题标题】:How to rewrite this simple unDRY laravel method如何重写这个简单的 unDRY laravel 方法
【发布时间】:2014-07-03 09:26:00
【问题描述】:

我想知道如何将以下用户模型雄辩的业务逻辑重写为更干一点。我将三个参数传递给模型,其中所有参数都是可选的,以缩小数据库搜索范围。我确信必须有一种优雅的方式来做到这一点,但目前它超出了我的能力范围。

public function guests_age($location_id, $year, $gender)
{
    if($location_id && $year && $gender)
    {
        return Guest::select('age')
            ->where('location_id', '=', $location)
            ->where('created_at', '=', $year)
            ->where('gender', '=', $gender)
            ->get();
    }
    elseif($location_id && $year && !$gender)
    {
        return Guest::select('age')
            ->where('location_id', '=', $location)
            ->where('created_at', '=', $year)
            ->get();
    }
    elseif($location_id && !$year && !$gender)
    {
        return Guest::select('age')
            ->where('location_id', '=', $location)
            ->get();
    }
   ... and so on to cover all cases...

}

感谢您的帮助。

【问题讨论】:

    标签: php laravel model eloquent dry


    【解决方案1】:

    试试这个方法

    public function guests_age($location_id, $year, $gender)
    {
    
        $this->qry = Guest::select('age');
    
        if($location_id)
        {
            $this->qry->where('location_id', '=', $location);
    
        }
        if($year)
        {
            $this->qry->->where('created_at', '=', $year)
    
        }
        if($gender)
        {
    
            $this->qry->where('gender', '=', $gender)
    
        }
    
        return $this->qry->get()
       ... and so on to cover all cases...
    
    }
    

    【讨论】:

    • 太棒了!谢谢!这可能是一个非常愚蠢的问题,但我如何在我的控制器中访问这个函数(放置在我的模型中)?当我执行 $guests_age = guest_age(); 时,我只会得到“调用未定义函数 guest_age()”;
    • 为您的模型创建一个对象,例如 $this->testMode = new Modelclass(); $this->testMode->Modelfunction();
    【解决方案2】:
    public function guests_age($args = array())
    {
        $columns = array('location_id', 'created_at', 'gender');
        $query = Guest::select('age');
    
        foreach($columns as $column)
        {
            if(!empty($args[$column]))
                $query = $query->where($column, $args[$column]);
        }
    
        return $query->get();        
    }
    
    //usage:
    guests_age(array('location_id' => '1'));
    guests_age(array('location_id' => '1', 'gender' => 'm'));
    //etc..
    

    【讨论】:

    • 超级紧凑和聪明!谢谢!我会把它保存在我的代码笔记本中。感谢您的快速回复。
    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多