我在使用 whereIn()
函数时遇到问题。
我有两个 table 推车和元素。 Carts 存储用户 ID 和商品 ID,而 items 表存储商品 ID 和商品信息。
我想要做的是获取购物车表中包含登录用户 ID 的所有商品。
现在我首先获取与活跃用户匹配的项目 ID:
$IDs = Cart::select('item_id')->where('user_id', auth()->id());
然后我想选择 ID 在 $IDs
中的所有项目
$items = Item::all()->whereIn('id', function($query) {
$query->select('item_id')->from($IDs->item_id);
});
但是当我尝试这个时,我收到错误
Object of class Illuminate\Database\Query\Builder could not be converted to int.
当我将 $IDs
替换为 [1234, 4321]
时,它就可以工作了。
如何解决这个问题?
最佳答案
$IDs = Cart::select('item_id')->where('user_id', auth()->id());
此行返回一个查询生成器而不是 ID 集合...
无论如何,您可以获取数组中的 ids 并将其直接用于 whereIn :
$IDs = Cart::where('user_id', auth()->id())->pluck('item_id')->all();
$items = Item::whereIn('id',$IDs)->get();
关于php - 将 whereIn 与 Laravel 中单独查询的值一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63397904/