how to make laravel query builder like codeigniter active record
Asked Answered
P

2

1

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.

Penney answered 8/10, 2013 at 17:58 Comment(1)
There isn't any method to do this yet but a pull request was submitted recently. You can review it and say what you think about it here : github.com/laravel/framework/pull/3108.Batt
P
4

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'));
Pediment answered 8/10, 2013 at 19:19 Comment(0)
J
1
$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();
    }

}
Jecon answered 8/10, 2013 at 19:15 Comment(1)
thanks for your answer bro... is Laravel self didn't have method to handle that condition?Penney

© 2022 - 2024 — McMap. All rights reserved.