账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Laravel定义了scopeXX方法后,在调用的时候出现where语句问题
    45
    0

    先上一下代码
    TopicController

    public function show(Category $category, Topic $topic)
    {
            $order = request('order');
    
            //$topics = $topic->where('category_id', $category->id)->withOrder($order)->paginate(20); //返回数据不正常,这个where并没有生效
            $topics = $topic->withOrder($order)->where('category_id', $category->id)->paginate(20);
            
            
            return view('topics.index', compact('topics', 'category'));
    }

    withOrder方法是在AppModelsTopic.php中定义

        // 通过控制器传过来的order进行话题排序
        public function scopeWithOrder($query, $order)
        {
            switch ($order) {
                case 'recent':
                    $query = $this->recent();
                    break;
                
                default:
                    $query = $this->recentReplied();
                    break;
            }
            // 这里调用with方法是为了防止N+1的问题
            return $query->with('user', 'category');
        }
    
        // 按照创建时间倒序排列
        public function scopeRecent($query)
        {
            return $query->orderBy('created_at', 'desc');   
        }
    
        public function scopeRecentReplied($query)
        {
            return $query->orderBy('updated_at', 'desc');
        }

    实现的逻辑是查询某一个分类下的所有帖子列表。疑惑的问题就是在show方法中如果我先调用withOrder在调用where语句那么结果是正常的。
    这是debug打出的sql

    select * from `topics` where `category_id` = '1' order by `updated_at` desc limit 20 offset 0

    如果我先使用$topic->where('oo', 'xx')->withOrder('oo', 'xx')那么这个where并没有生效。
    下面这个是debug打出的sql

    select * from `topics` order by `updated_at` desc limit 20 offset 0

    所以我想问问laravel这底层是如何处理的。谢谢大家

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 琉离 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部