如何制作像codeigniter活动记录这样的laravel查询构建器

how to make laravel query builder like codeigniter active record(如何制作像codeigniter活动记录这样的laravel查询构建器)
本文介绍了如何制作像codeigniter活动记录这样的laravel查询构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Laravel 4 查询生成器时遇到问题,我想创建一个可重用的方法

I have a problem with Laravel 4 query builder, i want make a re-usable method

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 中很容易将数组传递给活动记录:

In CodeIgniter it easy to passing array to active record :

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

Any idea how to have it on Laravel 4 query builder? I have googling but not find any answer. Thanks before.

推荐答案

你可以试试这个(假设这个函数在你的 User 模型中)

You may try this (Assumed, this function is in your User model)

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, = is optional. Call it like

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

这篇关于如何制作像codeigniter活动记录这样的laravel查询构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)