简体   繁体   English

将 whereIn 与来自 Laravel 中的单独查询的值一起使用

[英]Use whereIn with values from a seperate query in Laravel

I'm having trouble with the whereIn() function.我在使用whereIn() function 时遇到问题。

I have two tables carts and items.我有两张桌子推车和物品。 Carts stores user IDs and item IDs, while the items table stores item IDs and item information. Carts 存储用户 ID 和项目 ID,而 items 表存储项目 ID 和项目信息。

What I would like to do is get all items that are in the cart table with in the signed in users ID.我想要做的是在登录用户 ID 中获取购物车表中的所有项目。

Right now I'm first getting the item ID's matching the active user:现在我首先得到与活动用户匹配的项目 ID:

$IDs = Cart::select('item_id')->where('user_id', auth()->id());

Then I want to select all items with an ID in $IDs然后我想 select 所有 ID 为$IDs的项目

$items = Item::all()->whereIn('id', function($query) {
    $query->select('item_id')->from($IDs->item_id);
});

However when I try this, I get the error但是,当我尝试这个时,我得到了错误

Object of class Illuminate\Database\Query\Builder could not be converted to int. Object 的 class Illuminate\Database\Query\Builder 无法转换为 int。

When I replace $IDs with something like [1234, 4321] , it works.当我用[1234, 4321]之类的东西替换$IDs时,它可以工作。

How can I fix this problem?我该如何解决这个问题?

$IDs = Cart::select('item_id')->where('user_id', auth()->id());

this line return a query builder not a collection of ids...此行返回查询生成器而不是 id 集合...

anyway you can get the ids in array and use it directly for whereIn:无论如何,您可以获取数组中的 id 并将其直接用于 whereIn:

$IDs = Cart::where('user_id', auth()->id())->pluck('item_id')->all();

$items = Item::whereIn('id',$IDs)->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM