laravel 一对一唯一约束

标签 laravel eloquent relational-database

我有一对一的单向关系。

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'
]);

最佳答案

你可以:

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

关于laravel 一对一唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540998/

相关文章:

php - 在两张 table 上 Eloquent Laravel

php - 在 WHERE 中应用 OR 子句或在 Eloquent laravel 中应用 HAVING

mysql - 使用 MySQL 的关系模式

php - 在 Laravel Controller 中处理文件上传

php - 如何在 Laravel 中按字母顺序对记录进行排序

php - 显式定义 $guarded= ['id' ] 以防止意外插入?

laravel - 未添加验证用户

sql - 对于简单值的键值对,关系型数据库不就不如Redis这样的No-SQL数据库吗?

sql-server - 关系数据库中的许多表到一行

laravel - 多授权使用一页登录laravel