在 Laravel 中获取具有另一个 Eloquent 查询 ID 的所有项目
Getting all items with another Eloquent query ID in Laravel
我有这样的东西:
$items = Item::whereIn("name", $request["names"])->get();
现在我想获得拥有这些商品的商店列表。像这样:
$shops = Shop::whereIn("item_id", $items)->get();
这不起作用,因为 items 是一个 eloquent 集合(很明显)。我可以做一些循环并像这样获取所有 ID:
foreach ($items as $item){
$itemIds[] = $item
}
然后再用,不过我觉得肯定有更干净的方法。
有什么帮助吗?
使用->pluck('id')
和whereIn()
:
$items = Item::where('name', $request['names'])->get();
$shops = Shop::whereIn('item_id', $items->pluck('id'))->get();
Eloquent 集合可以访问 Laravel 的集合的许多相同功能 Class:
https://laravel.com/docs/9.x/collections#available-methods
->pluck('id')
将 return 所有 items.id
记录的数组,然后您可以使用它通过 ->whereIn('item_id', ...);
进行查询
我有这样的东西:
$items = Item::whereIn("name", $request["names"])->get();
现在我想获得拥有这些商品的商店列表。像这样:
$shops = Shop::whereIn("item_id", $items)->get();
这不起作用,因为 items 是一个 eloquent 集合(很明显)。我可以做一些循环并像这样获取所有 ID:
foreach ($items as $item){
$itemIds[] = $item
}
然后再用,不过我觉得肯定有更干净的方法。
有什么帮助吗?
使用->pluck('id')
和whereIn()
:
$items = Item::where('name', $request['names'])->get();
$shops = Shop::whereIn('item_id', $items->pluck('id'))->get();
Eloquent 集合可以访问 Laravel 的集合的许多相同功能 Class:
https://laravel.com/docs/9.x/collections#available-methods
->pluck('id')
将 return 所有 items.id
记录的数组,然后您可以使用它通过 ->whereIn('item_id', ...);