Php 如何获取在laravel中只有子数据的父数据
我试图从只有一个孩子的父母那里获取所有数据。请看下面我的代码Php 如何获取在laravel中只有子数据的父数据,php,laravel,Php,Laravel,我试图从只有一个孩子的父母那里获取所有数据。请看下面我的代码 $customers = Customer::with(['items' => function($query){ return $query->where('status', 2); }])->get(); dd($customers); 但是上面的代码返回所有客户。顺便说一下,我用的是Laravel4.2 项目表: 客户表: 您应该使用whereHas
$customers = Customer::with(['items' => function($query){
return $query->where('status', 2);
}])->get();
dd($customers);
但是上面的代码返回所有客户。顺便说一下,我用的是Laravel4.2
项目表:
客户表:
您应该使用
whereHas
notwith
检查子项的存在
$customers = Customer::whereHas('items', function($query){
return $query->where('status', 2);
})->get();
dd($customers);
我假设您已经定义了客户
和项目
之间的正确关系您应该尝试以下方法:
$customers = Customer::whereHas('items', function($query){
$query->where('status', 2);
})->get();
dd($customers);
with()用于快速加载。这基本上意味着,沿着主模型,Laravel将预加载您指定的关系。如果您有一组模型,并且希望为所有模型加载一个关系,那么这将特别有用。因为使用渴望加载时,您只运行一个额外的DB查询,而不是针对集合中的每个模型运行一个查询
has()是根据关系过滤选择的模型。因此,它的行为非常类似于正常的WHERE条件。如果您只使用has('relation'),这意味着您只想获取在该关系中至少有一个相关模型的模型
e、 g:
whereHas()的工作原理与has()基本相同,但允许您为要检查的相关模型指定其他过滤器
e、 g
将group by添加到计算总和中
这是我的代码中的另一个示例:
Customer::select(['customer.name', DB::raw('sum(sale.amount_to_pay) AS total_amount'), 'customer.id'])
->where('customer.store_id', User::storeId())
->join('sale', 'sale.customer_id', '=', 'customer.id')
->groupBy('customer.id', 'customer.name')
->orderBy('total_amount', 'desc')
->take($i)
->get()
就你而言:
Customer::select(['customer_id', DB::raw('sum(quantity) AS total')])
->whereHas('items', function ($q) {
$q->where('status', 2);
})
->groupBy('customer_id')
->get();
whereHas()允许您筛选数据或查询案例中的相关模型
拥有项目且it状态为2的客户
afetr获取我们正在执行的数据->groupBy('customer\u id')
GROUPBY语句通常与聚合函数(COUNT、MAX、MIN、SUM、AVG)一起使用,将结果集按一列或多列进行分组
选择(['customer_id',DB::raw('sum(quantity)AS total'))
这将选择客户id并计算数量总和列
Customer::select(['items.customer_id',DB::raw('count(items.id) AS total_qty')])
->join('items', 'items.user_id', '=', 'customer.customer_id')
->groupBy('items.customer_id')
->havingRaw('total_qty > 2')
->get();
或
正确的表名和列名。您是否在客户和项目之间创建了关系?并显示客户型号代码。它正在工作。还有一个问题。如何按客户对其进行分组,以便使用每个客户的
quantity
字段对数量进行汇总。它正在工作。还有一个问题。如何按客户分组,以便我可以使用每个客户的quantity
字段对数量进行汇总。能否显示表格格式,以便我能很好地理解。在get()之前使用groupBY();e、 g:->groupBY('customer_id')Hi-Dhruv。我可以用“在你的情况下”部分来解释一下吗?这样我就能明白发生了什么。谢谢。我的意思是,请在那部分加上解释。你也能加上解释吗?为什么我们在DB raw中有count()
?这不是总和吗?总和()和计数()我不使用db FIDLE。我已经包含了我的表字段的屏幕截图。但我无法在屏幕截图中测试查询:)
Customer::select(['customer_id', DB::raw('sum(quantity) AS total')])
->whereHas('items', function ($q) {
$q->where('status', 2);
})
->groupBy('customer_id')
->get();
Customer::select(['items.customer_id',DB::raw('count(items.id) AS total_qty')])
->join('items', 'items.user_id', '=', 'customer.customer_id')
->groupBy('items.customer_id')
->havingRaw('total_qty > 2')
->get();
$data=DB::select("select `items`.`customer_id`, count(items.id) AS total_qty
from `customers`
inner join `items`
on `items`.`customer_id` = `customers`.`customer_id`
group by `items`.`customer_id` having total_qty >= 2");