Laravel 在关系中对集合使用 unique

通过此代码从数据库中获取数据:


$allTickets = Ticket::with(['user','replies','supporters'])->whereUserId(auth()->user()->id)->get();

为我返回这个结果,它在数组中有 2 个索引,并且我有supporters关系的所有这些项目都是相同的,现在我的问题是我如何unique使用collections


Illuminate\Database\Eloquent\Collection {#1550 ▼

  #items: array:2 [▼

    0 => Modules\Ticket\Entities\Ticket {#1548 ▼

      #guarded: array:1 [▶]

      #connection: "mysql"

      #table: "tickets"

      ...

      #relations: array:3 [▼

        "user" => App\User {#1575 ▶}

        "replies" => Illuminate\Database\Eloquent\Collection {#1565 ▶}

        "supporters" => Illuminate\Database\Eloquent\Collection {#1572 ▼

          #items: array:1 [▼

            0 => App\User {#1585 ▼

              ...

              #attributes: array:19 [▼

                "id" => 1

                "user_id" => null

                ...

                "api_token" => "a"

                "remember_token" => null

                "deleted_at" => null

                "created_at" => "2020-06-14 13:56:45"

                "updated_at" => "2020-06-14 13:56:45"

              ]

              ...

            }

          ]

        }

      ]

      ...

    }

    1 => Modules\Ticket\Entities\Ticket {#1567 ▼

      #guarded: array:1 [▶]

      #connection: "mysql"

      #table: "tickets"

      ...

      #relations: array:3 [▼

        "user" => App\User {#1575 ▶}

        "replies" => Illuminate\Database\Eloquent\Collection {#1551 ▶}

        "supporters" => Illuminate\Database\Eloquent\Collection {#1559 ▼

          #items: array:1 [▼

            0 => App\User {#1585 ▼

              ...

              #attributes: array:19 [▼

                "id" => 1

                "user_id" => null

                ...

                "api_token" => "a"

                "remember_token" => null

                "deleted_at" => null

                "created_at" => "2020-06-14 13:56:45"

                "updated_at" => "2020-06-14 13:56:45"

              ]

              ...

            }

          ]

        }

      ]

      ...

    }

  ]

}



慕妹3242003
浏览 148回答 2
2回答

一只名叫tom的猫

不要尝试在集合上做唯一,尝试让你的数据已经从你的数据库中过滤出来。您可以按任何关系属性进行分组,只需传入一个闭包来处理对急切加载内容的查询,例如:$allTickets = Ticket::with(['user','replies'])->with([    'supporters' => function($query) {        $query->groupBy('id');    }])->whereUserId(auth()->user()->id)->get();

慕神8447489

或者您可以这样查询:$allTickets = collect(Ticket::with(['user','replies','supporters'])->whereUserId(auth()->user()->id)->get());$allUniqueTickets = $allTickets->unique();$tickets = $allUniqueTickets->values()->all();这就是您可以轻松地从控制器获取所有唯一值的方法。我希望这回答了你的问题。
打开App,查看更多内容
随时随地看视频慕课网APP