如何使laravel查询生成器像codeigniter活动记录

时间:2013-10-08 17:58:25

标签: php laravel laravel-4 query-builder

我在使用Laravel 4查询构建器时遇到问题,我想制作一个可重复使用的方法

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
}

在CodeIgniter中,将数组传递给活动记录很容易:

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'

知道如何在Laravel 4查询构建器上使用它吗?我有谷歌搜索但没有找到任何答案。谢谢。

2 个答案:

答案 0 :(得分:3)

你可以试试这个(假设,这个功能在你的User模型中)

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();
    }
}

请注意,=是可选的。称之为

$data = User::getData(array('first_name' => 'Jhon'));

答案 1 :(得分: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();
    }

}