Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

php - how to make laravel query builder like codeigniter active record

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

public function getData($where=array())
{
    // $where = array('city' => 'jakarta', 'age' => '25');
    return User::where($where)->get();

    // this will produce an error, because i think laravel didn't support it
}

In CodeIgniter it easy to passing array to active record :

public function getData($where=array())
{
    $rs = $this->db->where($where)->from('user')->get();

    return $rs->result();
}

// it will produce :
// SELECT * FROM user WHERE city = 'jakarta' AND age = '25'

Any idea how to have it on Laravel 4 query builder? I have googling but not find any answer. Thanks before.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...