【问题标题】:how to make laravel query builder like codeigniter active record如何制作像codeigniter活动记录这样的laravel查询构建器
【发布时间】:2013-10-15 19:14:04
【问题描述】:

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

【问题讨论】:

标签: php laravel laravel-4 query-builder


【解决方案1】:

你可以试试这个(假设这个函数在你的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'));

【讨论】:

    【解决方案2】:
    $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();
        }
    
    }
    

    【讨论】:

    • 谢谢你的回答兄弟...... Laravel 自己没有办法处理这种情况吗?
    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    相关资源
    最近更新 更多