【问题标题】:customized function raw query in Laravel frameworkLaravel 框架中的自定义函数原始查询
【发布时间】:2014-03-07 14:06:36
【问题描述】:

请指出我可以在 Laravel 框架中在哪里添加自定义功能,或者安装中是否缺少某些内容? 我正在尝试使用该功能

public function select($query, $bindings = array())
{
    return $this->run($query, $bindings, function($me, $query, $bindings)
    {
        if ($me->pretending()) return array();

        // For select statements, we'll simply execute the query and return an array
        // of the database result set. Each element in the array will be a single
        // row from the database table, and will either be an array or objects.
        $statement = $me->getPdo()->prepare($query);

        $statement->execute($me->prepareBindings($bindings));

        return $statement->fetchAll($me->getFetchMode());
    });
}

来自教程http://fideloper.com/laravel-raw-queries 但我找不到在哪里修改我现有的 Laravel 框架。

我需要运行一个从 3 个表进行内部连接的查询,并收集数据并将其发布到网格中。我需要在 Laravel 框架中进行修改并创建自己的功能。

请帮忙。 谢谢。

【问题讨论】:

  • 好的,解释一下你想做什么?我不明白为什么您需要创建自己的功能?查询生成器不能做什么?
  • 你的意思是使用查询生成器,我可以输入任何查询并调用查询来运行并从所需的数据库中获取数据?
  • 这是 laravel 文档的例子。有了这个开始,你可以做你想做的事。$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status' , '', 1) ->groupBy('status') ->get();
  • 请问我可以通过这样的查询吗? typedetarif_idtypedetarif INNER JOIN typedechambre ON typedechambre.idtypedechambre= $tablename.typedechambre_idtypedechambre INNER JOIN brochurehotel ON brochurehotel.idbrochurehotel= $tablename.brochurehotel_idbrochurehotel WHERE tarifhotel.idtarifhotel = '$idtarifhotel' AND brochurehotel.idbrochurehotel = '$idbrochure'
  • 是的,你当然可以忘记查询生成器,只传递你写的字符串,只需使用它:DB::raw('sql expression here');

标签: php mysql performance function laravel-4


【解决方案1】:

是的,所以在您的控制器中,您有对应于路由的方法。 所以选择你的路由对应的方法,在那个方法中调用这个函数。

例如在您的 HomeController.php 中

Class HomeController extends BaseController {
    public function index() {
        $yourData = DB::raw('your query');
        // if you want to inject it in your view.
        return View::make('yourtemplatename', ['yourdata' => $yourData]);
    }
}

在你的文件 routes.php 中

route::get('/', 'HomeController@index');

但是使用 Eloquent 进行查询有最漂亮的方法。 请查看相关文档。您的查询并不像看起来像一个连接森林那么难。

【讨论】:

  • 谢谢你,它是否必须在函数 index() 中,因为我已经有 public function index() { // 得到所有的书呆子 $nerds = Nerd::all(); // 加载视图并传递 nerds return View::make('nerds.index') ->with('nerds', $nerds); }
猜你喜欢
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 2018-02-01
  • 2021-03-02
相关资源
最近更新 更多