伪代码 - 说我有模型Author
,Document
,Revisions
,Editor
。
Author
hasMany Document
Document
hasMany Revisions
Document
hasMany Editors
(存储在修订表中)
但是下表结构:
作者模型:id
,name
,email
文档模型:id
,author_id
,title
修订模型:id
,document_id
,editor_id
,text
,saved_at
编辑模型:id
,name
,email
第一个问题 - 存储修订历史(包括哪个编辑器在哪个时间更改了文本);这是一个理想的结构吗?我希望能够$author->documents->where('title', 'Some title')->editor->name
;
要从Editor
访问Document
,是否值得直接在Document
构造函数中设置属性:
public function __construct(array $attributes = [] ){
$this->setRawAttributes(
array_merge($this->attributes,
$this->revisions()->orderBy('saved_at', 'desc')->first()->attributesToArray()
)
);
}
或者在模型中使用mutator:
public function getEditorIdAttribute($value){
return $this->revisions()->orderBy('saved_at', 'desc')->first()->editor_id;
}
或者是否有更好的方法来处理更像Laravel / Eloquent的修订?
答案 0 :(得分:1)
对于那些沿着这条路走下去的人 - 我无法在构造函数中设置属性并让它们在模型中可用,因此我使用了mutator。
每次调用mutator时都会阻止一个新的查询(如果你有一些mutator就会增加) - 我使用了一个简单的解决方法:
// Document Model
class Document extends Eloquent{
$this->latest = ''
// relations etc here
public function getSomeValueAttribute{
$this->getLatest('some_value');
}
public function getAnotherValueAttribute{
$this->getLatest('another_value');
}
public function getLatest($attr){
if(empty($this->latest)) $this->latest = $this->revisions->last();
return $this->latest->getAttribute($attr);
}
}
我确信我可以扩展getValueAttribute()
mutator以保持DRY,但上面的内容对我来说现在起作用,并且在设置关系之前调用mutators,因此它运行得很好。我也可以通过$document->revisions->get()
查看我的所有修订,或通过$document->text
查看最新值。