伪代码--假设我有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()
)
);
}
或者在模型中使用变异器:
public function getEditorIdAttribute($value){
return $this->revisions()->orderBy('saved_at', 'desc')->first()->editor_id;
}
还是有更好的方法来处理修订,更多的拉勒维尔/雄辩-喜欢?
发布于 2015-09-14 16:13:29
对于任何走上这条路的人--我无法在构造函数中设置属性并使它们在模型中可用,所以我求助于使用变异器。
为了防止每次调用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()
变送器以保持干燥,但是上面的方法目前对我来说是有效的,并且在建立关系之前调用了变异器,所以它运行得很好。我还可以通过$document->revisions->get()
看到我的所有修订,或者通过$document->text
看到最新的值。
https://stackoverflow.com/questions/32452774
复制相似问题