【发布时间】:2016-07-22 00:01:10
【问题描述】:
假设我有这 2 个模型 User 和 Account。
User 可以有多个 Accounts。 (有很多)
而Account 属于User。 (属于)
如果我不使用存储库,我会像这样保存模型及其关系:
$account = new Account();
$account->username = $this->username;
$account->secret = $this->secret;
$account->user()->associate($this->user);
$account->save();
当使用存储库时,我看到很多人(和文章)这样做:
$accountRepository->create([
'username' => $this->username,
'secret' => $this->secret,
'user_id' => $this->user()->id,
]);
我对这种方法的问题在于user_id,因为手动分配这种关系并不安全,另外当其他人阅读此代码时,他无法分辨Account 和User从那里!!
我目前的处理方式如下:(这是两种方式的结合)
// create the account and attach the fields and the relationships
$account = new Account();
$account->username = $this->username;
$account->secret = $this->secret;
$account->user()->associate($this->user);
// save the new created model with the repository
$account = $accountRepository->create($account->toArray());
但我不确定是否有更好的方法来做到这一点!
我所需要的只是使用associate 函数,因为它感觉更安全,并且对读者来说看起来更好。并使用存储库来保存和访问我的数据。
注意:我使用https://github.com/andersao/l5-repository 来抽象数据库层。
【问题讨论】:
-
哎呀,我希望有人回答你,我现在也在想同样的事情。
-
我也是!但也许您可以使用模型中的附加或存储库中的同步?
-
为什么您不能在您的帐户存储库中创建一个方法,例如 createWithUserAssociation()?然后您就可以将您的帐户数据和用户对象传递给它。
标签: laravel laravel-5 eloquent