Laravel在获得许多count()后返回错误最大准备语句

时间:2019-07-07 19:35:23

标签: mysql laravel

我从Laravel收到以下错误消息。

  

SQLSTATE [42000]:语法错误或访问冲突:1461无法创建   超过max_prepared_stmt_count条语句(当前值:16382)   (SQL:从guild中选择count(*)作为汇总)

我尝试删除公会计数语句,但这会使下一个SQL查询给出错误。

$users = User::count();
$crowdfunding = CrowdfundingSettings::find(1);
$guilds = Guild::count();
$data = [
    'totalItems' => ItemTemplate::totalCustomItems(),
    'totalAbilities' => Ability::totalCustom(),
    'totalMobs' => MobTemplate::all()->count(),
    'totalQuests' => Quest::all()->count(),
    'totalLootTables' => LootTable::all()->count(),
    'totalMerchantTables' => MerchantTable::all()->count(),
    'totalDialogue' => Dialogue::all()->count(),
    'totalCraftingRecipes' => CraftingRecipe::all()->count(),
    'totalItemSets' => ItemSetProfile::all()->count(),
    'totalSkills' => Skill::totalCustom()
];

return response()->json([
    'crowdfunding_settings' => $crowdfunding,
    'accounts' => $users,
    //'guilds' => $guilds,
    'data' => $data,
]);

我期望该语句产生结果,但出现错误。我将已准备好的最大语句数增加到32k,但仍然显示此错误,显示为16k。

2 个答案:

答案 0 :(得分:1)

正如Dimitri所提到的(并已确认here),当您只需要计数而不是模型本身中的数据时,不应使用->all()

像这样替换$data

    $data = [
        'totalItems' => ItemTemplate::totalCustomItems(),
        'totalAbilities' => Ability::totalCustom(),
        'totalMobs' => MobTemplate::count(),
        'totalQuests' => Quest::count(),
        'totalLootTables' => LootTable::count(),
        'totalMerchantTables' => MerchantTable::count(),
        'totalDialogue' => Dialogue::count(),
        'totalCraftingRecipes' => CraftingRecipe::count(),
        'totalItemSets' => ItemSetProfile::count(),
        'totalSkills' => Skill::totalCustom()
    ];

使用MobTemplate::all()->count()计算mob模板的数量将导致以下SQL SELECT * FROM mob_template;。结果将被加载到Eloquent集合中,然后该集合将计算它在PHP中包含的项目。这非常慢,占用大量内存,而且事实证明,准备好的语句也可能会引起问题。

使用MobTemplate::count()计算mob模板的数量将导致以下SQL SELECT COUNT(*) FROM mob_template;。这意味着数据库将为记录计数做所有繁重的工作,并且仅返回结果。这样,雄辩的人不必向集合中加载一堆数据,也不必计算PHP中的所有项目。

答案 1 :(得分:0)

确保执行后要处置PreparedQuery或其他任何准备好的SQL命令。处理呼叫ClosePreparedStatement。