【问题标题】:How to get the name of an ID from other table [LARAVEL]如何从其他表中获取 ID 的名称 [LARAVEL]
【发布时间】:2022-01-25 13:52:17
【问题描述】:

我所做的这个查询是获取service_id 及其在ServiceOrder 模型中的计数:

$test =  DB::table('serviceorders')
      ->select('serviceorders.service_id', DB::raw('COUNT(services.id) AS count'))
      ->join('services', 'serviceorders.service_id', '=', 'services.id')
      ->groupBy('serviceorders.service_id')
      ->whereMonth('serviceorders.created_at',Carbon::now("Asia/Kuala_Lumpur")->month)
      ->get();

我不知道如何获取 id 的名称,因为它位于另一个模型中

这是我dd($test)时的结果

如您所见,它显示 service_id 因为是的,我输入了,但我不知道如何获取 serviceName 。如果我尝试使用 chartJs 在饼图中显示它,这种查询方式也可能很困难(如果容易,请纠正我)

这些是涉及的表格

我也在寻找正确的方法来做到这一点。

【问题讨论】:

    标签: php sql laravel laravel-7


    【解决方案1】:

    你可以使用 Eloquent 函数:

    ServiceOrder::withCount('services')
                ->whereMonth('created_at', today()->month)
                ->having('services_count', '>', 0) // this is optional if you wish to avoid orders with 0 services
                ->get();
    // now you will have this attribute `services_count`
    
    // NOTE: Adjust your Carbon timezone within your `config/app.php` timezone to be 'Asia/Kuala_Lumpur'
    

    如果您的 ServiceOrder 模型中没有名为 services() 的关系(函数),它可能不起作用,而且我肯定猜到这是您的模型名称 :) 让我知道它是否不同,以便我可以帮忙。

    【讨论】:

    • 我可以知道它是什么 withCount('services') 。如果我想从服务订单中计算 service_id 怎么办?当我输入 service_id 时它不起作用,我确实在 serviceorder 模型中创建了关系,即调用服务模型的 serv()
    • 在这种情况下,将其更改为withCount('serv'),这意味着该属性现在称为serv_count,它将为您计算。并且请不要以这种方式命名您的关系,我的意思是“serv”根本不可读
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2020-05-05
    • 2015-07-29
    • 1970-01-01
    • 2011-02-25
    相关资源
    最近更新 更多