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条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装