我有一对一的单向关系。
class User extends Model
{
public $timestamps = false;
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public $timestamps = false;
}
我想创建一个具有单一配置文件的用户:
$user = User::firstOrCreate([
'name' => 'John',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="107a7f787e50757d71797c3e737f7d" rel="noreferrer noopener nofollow">[email protected]</a>'
]);
$profile = new Profile([
'age' => 'age',
'sex' => 'sex'
]);
$user->profile()->save($profile);
多次运行此命令会创建一个具有多个配置文件的用户,并且不会出现用户模型将具有多个关系的异常/警告。 如何创建限制或确保用户只有一份个人资料?
更新:
由于我的命令可以运行多次,profile_id
上的 unique
将引发异常,这在我的情况下并不理想。我最终做了这样的事情:
$user = User::firstOrCreate([
'name' => 'John',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7812171016381d15191114561b1715" rel="noreferrer noopener nofollow">[email protected]</a>'
]);
$user->profile()->firstOrCreate([
'age' => 'age',
'sex' => 'sex'
]);
最佳答案
你可以:
- 将
user_id
设置为unique()
- 手动检查配置文件是否已存在
$user->profile()->isEmpty()
- 使用
updateOrCreate()
或firstOrCreate()
方法。
关于laravel 一对一唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540998/