我在 Laravel 項(xiàng)目中通過 php artisan make:auth 命令生成了注冊表單。我想通過添加用戶在注冊時可以選擇他/她的性別的功能來對其進(jìn)行一些定制。我制作了具有性別列的性別表,其中包含兩個值 Man 和 Woman,并且還在 users 表中添加了 gender_id 列。我有很多關(guān)系,但是當(dāng)我嘗試注冊用戶時,他已注冊但 gender_id 列仍然為 NULL。我不知道錯誤在哪里。任何幫助表示贊賞。這是我的代碼。<?phpnamespace App;use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;class User extends Authenticatable{ use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'gender_id', 'name', 'email', 'password', 'age', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function genders() { return $this->belongsTo(Gender::class); }}
1 回答

一只萌萌小番薯
TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個贊
如果列設(shè)置不正確,Eloquent 關(guān)系可能不起作用。
在遷移中,列的類型gender_id必須是unsignedBigInteger
我建議您也將User.php模型中的函數(shù)重命名gender為genders
我看到您gender_id在創(chuàng)建用戶時使用:
$user = User::create([
'genders_id' => $genders,
'name' => $data['name'],
'email' => $data['email'],
'age' => $data['age'],
'password' => Hash::make($data['password']),
]);
這實(shí)際上不起作用,因?yàn)?Laravel 將gender_id在表中搜索
如果你想保留 genders_id,你可以hasMany這樣設(shè)置: return $this->hasMany(User::class, 'genders_id');
- 1 回答
- 0 關(guān)注
- 219 瀏覽
添加回答
舉報(bào)
0/150
提交
取消