【问题标题】:Handling revisions - setting attributes or mutators for relation columns处理修订 - 为关系列设置属性或修改器
【发布时间】:2015-09-15 08:21:41
【问题描述】:

伪代码 - 假设我有模型 AuthorDocumentRevisionsEditor

Author hasMany Document
Document hasMany Revisions
Document hasMany @987654330 @(存储在修订表中)

但表结构如下:

作者模型idnameemail
文档模型idauthor_idtitle
修订模型iddocument_ideditor_idtextsaved_at
编辑模型idname , email

第一个问题 - 存储修订历史(包括哪个编辑器在哪个时间更改了文本);这是一个理想的结构吗?我希望能够做到$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()
    )
  );
}

或者在模型中使用mutators:

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

或者有没有更好的方法来处理更像 Laravel/Eloquent 的修订?

【问题讨论】:

  • 许多好的问题会根据专家的经验产生一定程度的意见,但这个问题的答案往往几乎完全基于意见,而不是事实、参考资料或特定专业知识。
  • 我不太确定 - 在尝试了几件事后,我发现只有一个适用于上述情况,我已将其发布为答案。

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

对于任何走上这条路的人 - 我无法在构造函数中设置属性并让它们在模型中可用,所以我求助于使用 mutators。

为了防止每次调用 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 以保持干燥,但以上内容目前对我有用,并且在设置关系之前调用了mutator,因此它工作得很好。我还可以通过$document->revisions->get() 查看我的所有修订,或者通过$document->text 查看最新值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多