1

我对 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 查询生成器上使用它吗?我有谷歌搜索但没有找到任何答案。之前谢谢。

4

2 回答 2

4

你可以试试这个(假设这个功能在你的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'));
于 2013-10-08T19:19:21.617 回答
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();
    }

}
于 2013-10-08T19:15:53.147 回答