You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel子查询中调用User模型Scope方法的实现方案(无需复制代码)

问题:Eloquent子查询中调用模型Scope的方法

我在User.php模型中定义了一个针对用户表的Scope方法:

public function scopeWherePaidSubscriber(Builder $query)
{
    return $query->where(....)->where(...);
}

尝试在如下子查询中调用该Scope方法:

$count = UserCalendar::whereIn('user_id', function($que) { 
        $que->select('id')->from('user')->wherePaidSubscriber();
    })->distinct('user_id')->count();

但无法访问该Scope,报错信息如下:

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'paid_subscriber'

原因是未使用User::wherePaidSubscriber()的调用方式,Eloquent无法识别对应的Scope,反而尝试查找名为paid_subscriber的字段导致报错。请问有没有无需复制Scope代码就能调用它的方法?


解决方案

方法1:直接使用User模型的查询构造器

在子查询中直接基于User模型创建查询,这样就能正常调用已定义的Scope:

$count = UserCalendar::whereIn('user_id', User::select('id')->wherePaidSubscriber())
    ->distinct('user_id')
    ->count();

如果需要在闭包内操作,也可以这样写:

$count = UserCalendar::whereIn('user_id', function() { 
    return User::select('id')->wherePaidSubscriber();
})->distinct('user_id')->count();

方法2:手动调用Scope方法

Scope本质是接收QueryBuilder实例的类方法,可直接传入子查询的构造器对象调用:

$count = UserCalendar::whereIn('user_id', function($que) { 
    $que->select('id')->from('user');
    // 手动调用User模型的Scope方法
    (new User)->scopeWherePaidSubscriber($que);
})->distinct('user_id')->count();

方法3:转为全局Scope(按需使用)

如果该筛选逻辑需要在所有User查询中复用,可以将其改为全局Scope,这样无需手动调用就会自动应用条件。但此方式需根据业务场景判断是否合适,避免影响不需要该条件的查询。


内容的提问来源于stack exchange,提问作者The Blind Hawk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:05:22