【发布时间】:2021-01-07 02:00:51
【问题描述】:
我有一个 Profile 模型,它与 User 模型具有 OneToOne 关系。如何检查登录的用户是否已经有配置文件控制器?如果没有,请创建一个。
谢谢
【问题讨论】:
我有一个 Profile 模型,它与 User 模型具有 OneToOne 关系。如何检查登录的用户是否已经有配置文件控制器?如果没有,请创建一个。
谢谢
【问题讨论】:
试试这个
if (!$user->profile()->exists()) {
Profile::create(['user_id' => $user->id]);
}
或
if (!auth()->user()->profile()->exists()) {
Profile::create(['user_id' => $user->id]);
}
【讨论】:
在 laravel 中你可以检查关系是否存在
Auth::User()->has('profile')->exists();
或者
Auth::user()->profile()->exists();
或者
$profile = Auth::User()->profile()->first();
if (!$profile) // when doesn't exists
{
// code goes here
}
【讨论】:
您可以尝试使用firstOrCreate 来处理它:
$profile = $user->profile()->firstOrCreate([], [
'field' => 'value',
...
]);
【讨论】: