有没有更好的方法来使用存储库在 Laravel 中分配 Eloquent 关系?

Mah*_*alt 6 laravel eloquent laravel-5

假设我有这两个模型UserAccount.
其中 aUser可以有多个Accounts. (hasMany)
并且 anAccount属于 a User。(属于)

如果我使用存储库,我会像这样保存模型及其关系:

    $account = new Account();
    $account->username = $this->username;
    $account->secret = $this->secret;
    $account->user()->associate($this->user);
    $account->save();
Run Code Online (Sandbox Code Playgroud)

当使用 Repository 时,我看到很多人(和文章)这样做:

$accountRepository->create([
      'username' => $this->username,
      'secret'   => $this->secret,
      'user_id'  => $this->user()->id,
]);
Run Code Online (Sandbox Code Playgroud)

我对这种方法的问题在于,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());
Run Code Online (Sandbox Code Playgroud)

但我不确定是否有更好的方法来做到这一点!!我所需要的只是使用该associate功能,因为它让读者感觉更安全并且看起来更好。并使用存储库来保存和访问我的数据。

注意:我使用https://github.com/andersao/l5-repository来抽象数据库层。

pat*_*cus 0

您正在设计自己的存储库,因此您可以根据需要使功能明确。不要传入数据数组中的相关字段或对象,而是添加额外的依赖项作为额外参数。

class AccountRepository
{
    public function create($attributes, $user = null) {
        $account = new Account($attributes);
        
        if (!empty($user)) {
            $account->user()->associate($user);
        }
        
        $account->save();

        return $account;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以这样调用您的函数:

$accountRepository->create([
    'username' => $this->username,
    'secret'   => $this->secret,
], $this->user());
Run Code Online (Sandbox Code Playgroud)

现在您的调用代码只知道它正在调用的函数的依赖关系。它不需要知道它们如何关联的详细信息,或者必须设置的键来关联它们。它只知道User如果帐户需要 a,则该功能需要 a。