laravel 一对一的独特约束

Mir*_*c21 2 relational-database laravel eloquent

我有一个一对一的单向关系。

class User extends Model
{
    public $timestamps = false;

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

class Profile extends Model
{
    public $timestamps = false;
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个具有单个配置文件的用户:

$user = User::firstOrCreate([
    'name' => 'John', 
    'email' => 'john@email.com'
]);
$profile = new Profile([
    'age' => 'age', 
    'sex' => 'sex'
]);
$user->profile()->save($profile);
Run Code Online (Sandbox Code Playgroud)

多次运行此命令会创建一个具有多个配置文件的用户,而不会出现异常/警告用户模型将具有多个关系。如何创建约束或确保用户只有一个配置文件?

更新:

因为我的命令可以多次运行,所以uniqueonprofile_id会抛出一个异常,这对我来说并不理想。我最终做了这样的事情:

$user = User::firstOrCreate([
    'name' => 'John', 
    'email' => 'john@email.com'
]);
$user->profile()->firstOrCreate([
    'age' => 'age', 
    'sex' => 'sex'
]);
Run Code Online (Sandbox Code Playgroud)

Ale*_*nin 5

你可以:

  1. 设置user_idunique()
  2. 手动检查配置文件是否已存在 $user->profile()->isEmpty()
  3. 用途updateOrCreate()firstOrCreate()方法。