簡體   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