处理修订-设置关系列的属性或赋值函数


Handling revisions - setting attributes or mutators for relation columns

伪代码-比如我有型号AuthorDocumentRevisionsEditor

Author有许多Document
Document有许多Revisions
DocumenthasManyEditors(存储在修订表中(

但以下表格结构:

作者模型idnameemail
文档模型:idauthor_idtitle
修订模型iddocument_ideditor_idtextsaved_at
编辑器型号idnameemail

第一个问题-存储修订历史记录(包括哪个编辑在哪个时间更改了文本(;这是一个理想的结构吗?我希望能够做$author->documents->where('title', 'Some title')->editor->name

要从Document访问Editor,是否值得直接在Document构造函数中设置属性:

public function __construct(array $attributes = [] ){
  $this->setRawAttributes(
    array_merge($this->attributes, 
      $this->revisions()->orderBy('saved_at', 'desc')->first()->attributesToArray()
    )
  );
}

或者在模型中使用突变子:

public function getEditorIdAttribute($value){
  return $this->revisions()->orderBy('saved_at', 'desc')->first()->editor_id;
}

或者,有没有一种更好的方式来处理更像Laravel/Eloquent的修订?

对于任何走这条路的人来说,我无法在构造函数中设置属性,也无法在模型中使用它们,所以我只能使用赋值函数。

为了防止每次调用一个赋值函数时都出现新的查询(如果你有几个赋值函数,就会相加(,我使用了一个简单的解决方法:

// 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()突变体以保持干燥,但以上内容目前对我有效,并且在建立关系之前调用了突变体,所以它运行得很好。我还可以通过$document->revisions->get()查看我的所有修订,或者通过$document->text查看最新的值。