繁体   English   中英

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

[英]how to make laravel query builder like codeigniter active record

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

您可以尝试这个(假设,此功能在您的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();
    }
}

Rember that, =是可选的。 称之为

$data = User::getData(array('first_name' => 'Jhon'));
$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();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM