簡體   English   中英

Laravel Eloquent 從多個表中查詢 Select 列

[英]Laravel Eloquent Query Select Column From Multiple Tables

我有一個 Laravel 后端和一個 VueJS 前端。

我正在嘗試對具有 hasOne 關系但僅 select 特定列從關系中的 model 生成查詢,進行求和和分組。

楷模

  • 合同(CONTRACT_TYPE,CONTRACT_PRICE)
  • 附加信息(START_DATE)

我的 Eloquent 查詢

public function contractsByYear() {
   return Contract::where('CONTRACT_TYPE','LIKE','SP-%')->with(['AdditionalInfo' => function($query) {
       $query->selectRaw('MONTH(START_DATE) as Month')->whereYear('START_DATE','2019');
   }])->sum('CONTRACT_PRICE')->groupBy('Month');
}

預期成績

MONTH | TOTAL
1     | 500
2     | 233
3     | 800
etc

我的問題是表結構存在,我無法編輯。 為什么 START_DATe 存儲在單獨的表中是我無法理解的。

收集方法可能會做你想要的

public function contractsByYear()
{
    return Contract::select('id', 'CONTRACT_PRICE') /* Only really need the id (or whatever else is the pk) and the price */
    ->where('CONTRACT_TYPE','LIKE','SP-%')
    ->with(['AdditionalInfo' => function($query) {
        $query->select('id', 'contract_id')         /* Only really need the id (or whatever else is the pk), and the Contract fk*/
        ->selectRaw('MONTH(START_DATE) as Month')   /* Aggregate the month */
        ->whereYear('START_DATE','2019');
    }])
    ->get()
    // From this point on, it's a Collection
    ->groupBy('AdditionalInfo.*.Month')             /* It's either this or 'AdditionalInfo.Month' */
    ->map(function($item, $key) {
        return [
            'month' => $key,
            'total' => $item->sum('CONTRACT_PRICE')
        ];
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM