问题描述:

I am working with Laravel 4 and I need to set some database queries in configuration files. For example:

config/prod/queries.php

config/stage/qieries.php

And I want to call them like

DB::connection ( 'mysql' )->select ( Config::get('queries.test'););

The case is that my query has some params and some filters. For example:

 select * from table where some_date between '$today' and '$tomorrow'

And if I just put this query in the config files and call it, of course exception for unknown variables $today and $tomorrow occures.

How can I do this ?

网友答案:

In your configuration file

            return array(
               "query1"=> "select * from table where some_date between ? and ?"
            );

In your program,e.g controller

            $query = Config::get("query")['query1'];
            $result = DB::select($query,array("1970-01-01","2014-01-01"));
网友答案:

How about this approach:

config file:

return [
  "select:logs-between-dates" => "select * from logs where date between ? and ?",
  "select:logs-not-between-dates" => "select * from logs where date not between ? and ?"
];

class that extends DB logic:

class Query extends DB {
  public static $queries = [];

  public static function select($name, $params = []) {
    return self::select(self::$queries['select:'.$name], $params);
  }
}

initialization:

Query::$queries = Config::get("query");

usage:

$result = Query::select('logs-between-dates', ["1970-01-01","2014-01-01"]);
相关阅读:
Top