基本上,如果在另一个符合某些条件的表中有记录,我尝试使用查询构建器从表中选择所有内容。目前我有下面的代码,但是在100K行的表格上它的速度非常慢。
$result= [];
$customers = (array)DB::table('customers')->where('lastName','LIKE', Input::get('letter').'%')->orderBy('lastName','ASC')->get();
foreach($customers as $k => $v)
{
if(DB::table('orders')->where('disabled','=','')->where('customerId','=',$v->id)->where('status','!=',0)->count() > 0)
{
array_push($result, $v);
}
}
任何建议都将不胜感激!此刻,这个时间在5分钟后消失。
答案 0 :(得分:1)
目前,您正在运行一个查询来获取客户,然后查询每个客户以获取相关订单。如果您有许多客户,则会导致需要执行大量查询。
您可以通过加入这两个表来执行单个查询。
这样可以解决问题:
//get all customers
$results = DB::table('customers')
//filter customers by lastName
->where('customers.lastName','LIKE', Input::get('letter').'%')
//take only customers that have orders matching criteria below
->join('orders', function($query) {
//link customer to their orders
$join->on('orders.customerId', '=', 'customers.id');
//consider only enabled orders
$join->where('orders.disabled','=','');
//consider only orders where status != 0
$join->where('orders.status','!=',0);
})
//if customer has multiple orders matching criteria
//they will be returned multiple time, so you need to group by
//customers.id to get only one row per customer
->groupBy('customers.id')
//order by customers last name
->orderBy('customers.lastName','ASC')
->get();
答案 1 :(得分:0)
你可以尝试这样的事情
$data = Customer::with('Order') -> where('lastName','like',$name) -> whereExists(function($query){
$query->select(DB::raw(1)) -> from('orders')
->whereRaw('orders.customer_id= customer.id')
->where('disabled','=','')
->where('status','!=',0);
})-> orderBy('lastname','ASC') -> get() ->toArray();