通过此代码从数据库中获取数据:$allTickets = Ticket::with(['user','replies','supporters'])->whereUserId(auth()->user()->id)->get();为我返回这个结果,它在数组中有 2 个索引,并且我有supporters关系的所有这些项目都是相同的,现在我的问题是我如何unique使用collectionsIlluminate\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" ] ... } ] } ] ... } ]}
2 回答
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
不要尝试在集合上做唯一,尝试让你的数据已经从你的数据库中过滤出来。您可以按任何关系属性进行分组,只需传入一个闭包来处理对急切加载内容的查询,例如:
$allTickets = Ticket::with(['user','replies'])->with([
'supporters' => function($query) {
$query->groupBy('id');
}
])->whereUserId(auth()->user()->id)->get();
慕神8447489
TA贡献1780条经验 获得超1个赞
或者您可以这样查询:
$allTickets = collect(Ticket::with(['user','replies','supporters'])->whereUserId(auth()->user()->id)->get());
$allUniqueTickets = $allTickets->unique();
$tickets = $allUniqueTickets->values()->all();
这就是您可以轻松地从控制器获取所有唯一值的方法。我希望这回答了你的问题。
- 2 回答
- 0 关注
- 135 浏览
添加回答
举报
0/150
提交
取消