【问题标题】:Refactor whereHas to use via global scopes in Laravel通过 Laravel 中的全局范围重构 whereHas 使用
【发布时间】:2019-03-24 19:50:30
【问题描述】:

我有 2 个模型,CoreChallengeChallenge。下面是表之间的关系。

我想获取Challenges,其中core_challenges 处于活动状态。我试图将全局范围放在CoreChallenge 模型中,但是当Corechallengeinactive 时,我得到null 的关系。

我是这样做的

$challenges = Challenge::with('core_challenge')->whereHas('core_challenge', function($q){
            $q->where('status', '=', 'active');
        })->get();

我想用全局作用域来做

CoreChallenge 上的全局范围给了我 null,但我希望它的父级 (Challenge) 甚至不应该加载,就像在 whereHas 中一样。有什么办法吗?

【问题讨论】:

    标签: laravel-5 eloquent relationship


    【解决方案1】:

    我偶然发现了同样的方法,但是当表格变大时(在您的场景中为 core_challenges_table),whereHas 最终变得非常慢(大约 1 分钟响应时间)。

    所以我使用了这样的解决方案:

    $ids = CoreChallenge::where('status', 'active')->pluck('id');
    
    $challenges = Challenge::with('core_challenges')
                            ->whereIn('core_challenge_id', $ids)
                            ->get();
    

    通过这种方法,我的查询从 1 分钟缩短到 600~ms。

    可以转化为模型作用域

    class Challenge {
    
       public function scopeActive($query) {
           $activeIds = CoreChallenge::where('status', 'active')->pluck('id');
    
           return $query->whereIn('core_challenge_id', $ids);
       }
    }
    
    Challenge::with('core_challenges')->active()->get();
    

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 2016-05-29
      • 2014-11-23
      • 2016-04-14
      • 1970-01-01
      • 2015-12-02
      • 2015-07-06
      • 1970-01-01
      相关资源
      最近更新 更多