dongzouban9871 2016-08-30 11:23
浏览 83
已采纳

如何在laravel sql查询中获得灵活性

I want to add a sql filter where('comment_id', '=', 1) to php code

$datas = $this->model->ADD HERE->orderBy('created_at', 'DESC')->paginate(15);

Trying to add the string to code take me hours. How to make it?


Here is my code:

CommentResource.php passing the sql filter as string parameter.

<?php
class CommentResource extends BaseResource
{    
    public function index()
    {
        $filter = "where('comment_id', '=', 1)";
        return parent::index_filter($filter);
    }

CommentResource.php

<?php
class BaseResource extends Controller
{
    protected function index_filter($filter)
    {
        $datas = $this->model->ADD HERE->orderBy('created_at', 'DESC')->paginate(15);
        return view($this->resourceView.'.index')->with('datas', $datas);
    }
}
  • 写回答

3条回答 默认 最新

  • douqian2524 2016-08-30 11:51
    关注

    As I understand you want to use different types of where as filters in your queries. That's why you want to make them dynamic. I would suggest the following solution for your task:

    <?php
    class CommentResource extends BaseResource
    {    
        public function index()
        {
            $filter = [ 'operator' => 'where', 'args' => ['comment_id', '=', 1]];
            return parent::index_filter($filter);
        }
    
    <?php
    class BaseResource extends Controller
    {
        protected function index_filter($filter)
        {
            $where = $filter['operator'];
            $args = $filter['args'];
            $datas = $this->model->$where(...$args)->orderBy('created_at', 'DESC')->paginate(15);
            return view($this->resourceView.'.index')->with('datas', $datas);
        }
    }
    

    However, it will work starting from Php5.6+ because of oeprator ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?