【问题标题】:Is there a better way to assign an Eloquent relationship in Laravel using a Repository?有没有更好的方法来使用存储库在 Laravel 中分配 Eloquent 关系?
【发布时间】:2016-07-22 00:01:10
【问题描述】:

假设我有这 2 个模型 UserAccount
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,因为手动分配这种关系并不安全,另外当其他人阅读此代码时,他无法分辨AccountUser从那里!!

我目前的处理方式如下:(这是两种方式的结合)

    // 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


【解决方案1】:

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

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

        return $account;
    }
}

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

$accountRepository->create([
    'username' => $this->username,
    'secret'   => $this->secret,
], $this->user());

现在你的调用代码只知道它调用的函数的依赖关系。它不需要知道它们是如何相关的细节,或者必须设置它们来关联它们的键。如果帐户需要,它只知道该函数需要User

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2021-02-23
    • 1970-01-01
    • 2015-10-19
    • 2015-07-27
    相关资源
    最近更新 更多