为什么我可以在一对一关系中提交多个记录?

Why can I submit more than one record in a one-to-one relationship?

我正在使用 Laravel 5.2。为什么我可以在一对一关系中提交多个记录?有两个table,userprofile,它们是一对一的关系。

用户:

class User extends Authenticatable
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

简介:

class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

我已经设置了一对一关系,但我可以通过一个用户帐户向 table profile 提交多条记录。这是为什么?

您的关系设置正确。 hasOnehasMany 之间的唯一区别是 hasOne 只会 return 第一个相关记录。没有什么可以阻止您尝试关联多个记录,但是当您检索相关记录时,您只会得到一个。

例如,给定以下代码:

$user = User::first();
$user->profile()->save(new Profile(['name' => 'first']));
$user->profile()->save(new Profile(['name' => 'second']));

$user->load('profile');
$echo $user->profile->name; // "first"

这是完全有效的代码。它将创建两个新的配置文件,每个配置文件都将 user_id 设置为指定的用户。但是,当您通过 $user->profile 访问相关配置文件时,它只会加载其中一个相关配置文件。如果您将其定义为 hasMany,它将加载所有相关配置文件的集合。

如果您想防止意外创建多个配置文件,您需要在代码中执行此操作:

$user = User::first();

// only create a profile if the user doesn't have one.
// don't use isset() or empty() here; they don't work with lazy loading.
if (!$user->profile) {
    $user->profile()->save(new Profile());
}