how to make laravel query builder like codeigniter active record

后端 未结 2 2001
死守一世寂寞
死守一世寂寞 2020-12-18 16:15

I have a problem with Laravel 4 query builder, i want make a re-usable method

public function getData($where=array())
{
    // $where = array(\'city\' =>          


        
相关标签:
2条回答
  • 2020-12-18 16:40
    $where[] = array(
       'field' => 'city',
        'operator' => '=',
        'value' => 'jakarta'
    );
    $where[] = array(
        'field' => 'age',
        'operator' => '=',
        'value' => 25
    );
    $data = getData($where);
    
    public function getData($wheres = array()){
    
        $query = User::query();
        if(!empty($wheres)){
           foreach($wheres as $where){
            {
                $query = $query->where($where['field'], $where['operator'], $where['value']);
            }
        $result = $query->get();
        }
    
    }
    
    0 讨论(0)
  • 2020-12-18 16:46

    You may try this (Assumed, this function is in your User model)

    class User extends Eloquent {
    
        public static function getData($where = null)
        {
            $query =  DB::table('User');
            if(!is_null($where )) {
                foreach($where as $k => $v){
                    $query->where($k, $v);
                }
            }
            return $query->get();
        }
    }
    

    Rember that, = is optional. Call it like

    $data = User::getData(array('first_name' => 'Jhon'));
    
    0 讨论(0)
提交回复
热议问题