Laravel查询存在的几种

问题描述

我阅读了有关查询生成器的Laravel文档,但是无法弄清楚:

当前情况: 我的用户模型有很多upperCategories,而我的upperCategory模型有很多subCategories。这就是为什么我可以这样做:auth()->user()->upperCategories()->with('subCategories')->get()->toArray(); 请注意,我正在使用紧急加载以提高性能。这段代码工作正常。它返回类似的内容

    [
       "id" => 1,"user_id" => 2,"category" => "Project","sub_categories" => [
         [
           "id" => 1,"upper_category_id" => 1,"category" => "myFristProject",],[
           "id" => 4,"category" => "mySecondProject",]

我想要什么: 我的SubCategory模型具有许多微类别。我想检查每个SubCategory是否存在microcategory,因此最后我可以创建类似以下内容

       [
           "id" => 1,"sub_categories" => [
             [
               "id" => 1,"micro_category_exists" => true,[
               "id" => 4,"micro_category_exists" => false,]

不想要的是为我拥有的每个子类别发送一个SQL查询。我知道我可以使用exist()方法解决类似的问题,但是我想在一个查询中完成所有操作。这可能吗?

解决方法

由于您想为 subCategories 关系添加一个额外的字段,您需要向 with 函数添加一个闭包

auth()->user()
    ->upperCategories()
    ->with([
        'subCategories' => function ($query) {
            $query->withCount('microCategories as micro_category_exists');
        }
    ])
    ->get()
    ->toArray();

这个简单的查询将加载 microCategories COUNT,为您提供如下内容:

"sub_categories" => [
    [
        "id" => 1,"upper_category_id" => 1,"category" => "myFristProject","micro_category_exists" => 5,],[
        "id" => 4,"category" => "mySecondProject","micro_category_exists" => 0,]

您可以将这些数字用作真/假值(0 可以在 php 中转换为 false)。

如果您真的想要查询中的真值,您需要编写一些自定义逻辑。在最新版本的 Laravel 中,存在 withAggregate 函数,这使得这非常容易。

auth()->user()
    ->upperCategories()
    ->with([
        'subCategories' => function ($query) {
            $query->withAggregate('microCategories as micro_category_exists','count(*) > 0');
        }
    ])
    ->get()
    ->toArray();
"sub_categories" => [
    [
        "id" => 1,"micro_category_exists" => true,"micro_category_exists" => false,]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...