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


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

我正在使用Laravel 5.2。为什么我可以在一对一关系中提交多条记录?有两个表,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);
    }
}

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

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

例如,给定以下代码:

$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());
}