【问题标题】:Use whereIn with values from a seperate query in Laravel将 whereIn 与 Laravel 中单独查询的值一起使用
【发布时间】:2020-12-03 11:08:38
【问题描述】:

我在使用 whereIn() 函数时遇到问题。

我有两张桌子推车和物品。 Carts 存储用户 ID 和商品 ID,而 items 表存储商品 ID 和商品信息。

我想要做的是获取购物车表中登录用户 ID 中的所有商品。

现在我首先获得与活动用户匹配的项目 ID:

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

然后我想选择$IDs中ID的所有项目

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

但是当我尝试这个时,我得到了错误

Illuminate\Database\Query\Builder 类的对象无法转换为 int。

当我将$IDs 替换为[1234, 4321] 之类的东西时,它可以工作。

我该如何解决这个问题?

【问题讨论】:

  • 不熟悉 Laravel,但你确定whereIn 甚至接受回调函数吗?
  • 另外,$IDs 无论如何都不会在您的回调函数中定义,除非您在匿名函数中添加 use 子句。
  • @Jeto 我很确定 whereIn 接受回调函数

标签: php mysql laravel


【解决方案1】:
$IDs = Cart::select('item_id')->where('user_id', auth()->id());

此行返回一个查询构建器,而不是一个 id 集合 ...

无论如何,您都可以获取数组中的 id 并将其直接用于 whereIn :

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

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

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 2015-07-06
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    相关资源
    最近更新 更多