首页 > 解决方案 > 如何在 laravel 集合的同一查询中使用 laravel 命令 'whereIn' 和 'WhereNotIn'

问题描述

从数据库中随机选择新产品时,我有一个可以正常工作的查询。但是为了防止重复,在我看来,我在页面上传递了一个已经在销售的产品的 JSON 对象。我希望我的查询基本上查询我的数据库以获取待售产品,但也不在已售产品的集合中。

这部分工作得很好

$nproduct = Product::whereIn('seller_id', Auth::user()->samegroup())->inRandomOrder()->first();
            $nprice = $nproduct->price;
            $nquantity = $nproduct->quantity_available;
            $nid = $nproduct->id;
            $nseller = $nproduct->seller_id;

但是当我试图确保我的查询不包含 $products_already_for_sale 中的任何内容时,我很挣扎

$products_already_for_sale = $request->current_product_ids;

标签: databaselaraveleloquent

解决方案


尝试这个

$products_already_for_sale = $request->current_product_ids; //it must be array []

$nproduct = Product::whereIn('seller_id', Auth::user()->samegroup())->whereNotIn('product_id',
$products_already_for_sale)->inRandomOrder()->first();

完全未经测试,但我认为这会工作


推荐阅读