[英]In a Laravel Model's relationship how do I return a relationship using GROUP BY and MAX?
我有一個項目,該項目可以有附加文件。 項目和文檔都是模型/表格。
簡化的示例文檔表:
-----------------------------------
| ID | filename | version |
-----------------------------------
| 1 | list.docx | 1 |
| 2 | list.docx | 2 |
| 3 | file.xls | 1 |
-----------------------------------
我想要一些簡單的版本控制,以便用戶可以“替換”文檔,新表行將復制ID和版本以外的所有先前條目值。
我的問題是我想使用一種關系來提取所有最新文檔。 我目前在Project模型中使用這種怪物:
public function latest_documents()
{
return $this->hasMany(Document::class)
->where('version', \DB::raw('(SELECT max(d.version) from documents d where d.filename = documents.filename)'))
}
一定會有更好的辦法? 我嘗試僅使用具有關系的groupBy()和max(),但出現錯誤。
編輯:在DB :: raw解決方案之前嘗試了“ Laravel方法”:
public function documents()
{
return $this->hasMany(Document::class)->groupBy('filename')->max('version');
}
錯誤:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
我的建議是基於文檔表創建一個MySQL視圖,該表始終僅包含最新的文檔文件,並僅與該視圖建立關系。 因此:
步驟1 /創建視圖:
create view latest_documents as
select filename,
max(version) as version,
project_id as project_id,
any_value(id) as id
from documents
group by project_id, filename;
步驟2 /創建視圖模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LatestDocument extends Model
{
//
}
步驟3 /將關系添加到項目模型:
public function latest_documents()
{
return $this->hasMany(LatestDocument::class);
}
我對此進行了測試,應該可以工作。
注意:我在第一步中使用了any_value()
來防止根據only_full_group_by
出現錯誤。 因此,如果您禁用了此模式(我不推薦),則無需在id
周圍使用此功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.