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

如何在stancl/tenancy包中遍历所有租户并切换当前租户?

解决方案:stancl/tenancy遍历并切换租户上下文

stancl/tenancy没有提供和Laravel/Multitenancy包中eachCurrent()完全一致的封装方法,但可以通过它内置的租户上下文切换API轻松实现相同功能,两种常用方式如下:

方式一:使用tenant->run()(推荐)

run()方法会自动封装租户上下文的初始化与销毁,是最简洁的实现方式:

use Stancl\Tenancy\Models\Tenant;

Tenant::all()->each(function ($tenant) {
    // 在当前租户的上下文环境中执行业务逻辑
    $tenant->run(function () {
        // 这里的代码将在该租户的数据库连接、环境配置下运行
        // 示例:获取该租户下的所有用户
        $users = \App\Models\User::all();
    });
});

方式二:手动控制上下文生命周期

如果需要更灵活的上下文管理(比如在租户逻辑前后执行额外操作),可以手动调用initialize()和end():

use Stancl\Tenancy\Models\Tenant;
use Stancl\Tenancy\Tenancy;

$tenancyService = app(Tenancy::class);

foreach (Tenant::all() as $tenant) {
    // 切换到当前租户上下文
    $tenancyService->initialize($tenant);
    
    // 执行租户专属逻辑
    $stats = \App\Models\Order::whereMonth('created_at', now()->month)->count();
    
    // 结束租户上下文,切回原环境
    $tenancyService->end();
}

注意事项

  • 如果在异步任务(如队列)中使用,确保每个任务独立管理租户上下文,避免交叉污染
  • 若租户数量较多,建议分批处理,避免内存占用过高

内容的提问来源于stack exchange,提问作者Čamo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:29:54