在Laravel如何做到这一点,子查询在哪里

我如何在Laravel中进行这个查询:

SELECT `p`.`id`, `p`.`name`, `p`.`img`, `p`.`safe_name`, `p`.`sku`, `p`.`productstatusid` FROM `products` p WHERE `p`.`id` IN ( SELECT `product_id` FROM `product_category` WHERE `category_id` IN ('223', '15') ) AND `p`.`active`=1 

我也可以通过连接来实现,但是我需要这种格式来提高性能。

提前致谢! 干杯,马克

考虑这个代码:

 Products::whereIn('id', function($query){ $query->select('paper_type_id') ->from(with(new ProductCategory)->getTable()) ->whereIn('category_id', ['223', '15']) ->where('active', 1); })->get(); 

看一下Fluent的高级文档: http : //laravel.com/docs/queries#advanced-wheres

以下是您要实现的一个示例:

 DB::table('users') ->whereIn('id', function($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id'); }) ->get(); 

这将产生:

 select * from users where id in ( select 1 from orders where orders.user_id = users.id ) 

您可以使用关键字“use($ category_id)”来使用variables

 $category_id = array('223','15'); Products::whereIn('id', function($query) use ($category_id){ $query->select('paper_type_id') ->from(with(new ProductCategory)->getTable()) ->whereIn('category_id', $category_id ) ->where('active', 1); })->get(); 

下面的代码为我工作:

 $result=DB::table('tablename') ->whereIn('columnName',function ($query) { $query->select('columnName2')->from('tableName2') ->Where('columnCondition','=','valueRequired'); }) ->get(); 

Laravel 4.2及更高版本,可能会使用尝试关系查询: –

 Products::whereHas('product_category', function($query) { $query->whereIn('category_id', ['223', '15']); }); public function product_category() { return $this->hasMany('product_category', 'product_id'); } 
 Product::from('products as p') ->join('product_category as pc','p.id','=','pc.product_id') ->select('p.*') ->where('p.active',1) ->whereIn('pc.category_id', ['223', '15']) ->get();