首页 > 解决方案 > 如何在laravel中获取只有子数据的父母数据

问题描述

我正在尝试从只有孩子的父母那里获取所有数据。请在下面查看我的代码。

$customers = Customer::with(['items' => function($query){
            return $query->where('status', 2);
        }])->get();

        dd($customers);

但是上面的代码返回了所有的客户。顺便说一句,我使用的是 laravel 4.2。

物品表: 在此处输入图像描述

客户表: 在此处输入图像描述

标签: phplaravel

解决方案


with()用于急切加载。这基本上意味着,沿着主模型,Laravel 将预加载您指定的关系。如果您有一组模型并且想要为所有模型加载关系,这将特别有用。因为通过预先加载,您只需运行一个额外的数据库查询,而不是为集合中的每个模型运行一个。

has()是根据关系过滤选择模型。所以它的行为与正常的 WHERE 条件非常相似。如果您只使用 has('relation') 这意味着您只想获取在此关系中至少具有一个相关模型的模型。

例如:

$users = Customer::has('items')->get();
// only Customer that have at least one item are contained in the collection

whereHas()的工作原理与 has() 基本相同,但允许您为相关模型指定额外的过滤器以进行检查。

例如

$users = Customer::whereHas('items', function($q){
    $q->where('status', 2);
})->get();
// only customer that have item status 2

添加 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() 允许您在您的情况下过滤数据或查询相关模型,这些客户拥有物品并且状态为 2

在获取我们正在执行的数据之后->groupBy('customer_id')

GROUP BY 语句通常与聚合函数(COUNT、MAX、MIN、SUM、AVG)一起使用,以按一列或多列对结果集进行分组。

select(['customer_id', DB::raw('sum(quantity) AS total')])这将选择客户 ID 并计算数量列的总和


推荐阅读