如何执行laravel中的两个where条件,其中order_id相同,但product_id在数组中



所以我有一个ordered_products表结构

我有订单id和多个产品id,现在我想根据订单id和产品id获取结果例如

orders_id =10 , products_ids = array(15,20,21,23)
$result = array();
foreach (products_ids as $value) {
$result=DB::table('ordered_products')->where('orders__id','=',10)->where('products_id','=',$value)->get();
}

我执行了查询,但只得到一行。请帮我执行查询。

您应该将where用于order_id,将whereIn用于product_ids

$result = DB::table('ordered_products')
->where('orders__id',10)
->whereIn('products_id', $products_ids)
->get();

目前,您正在为每个产品运行一个查询,每次都覆盖$result。您可以避免foreach循环,并使用whereIn获得所有结果。

$orders_id =10;
$products_ids = array(15,20,21,23)
$result=DB::table('ordered_products')
->where('orders__id','=',10)
->whereIn('products_id',$products_ids)
->get();

相关内容

最新更新