HasMany 关系在 Laravel 中不起作用

我在 Laravel 项目中通过 php artisan make:auth 命令生成了注册表单。我想通过添加用户在注册时可以选择他/她的性别的功能来对其进行一些定制。我制作了具有性别列的性别表,其中包含两个值 Man 和 Woman,并且还在 users 表中添加了 gender_id 列。我有很多关系,但是当我尝试注册用户时,他已注册但 gender_id 列仍然为 NULL。我不知道错误在哪里。任何帮助表示赞赏。这是我的代码。

<?php


namespace 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);

    }

}



慕村225694
浏览 167回答 1
1回答

一只萌萌小番薯

如果列设置不正确,Eloquent 关系可能不起作用。在迁移中,列的类型gender_id必须是unsignedBigInteger我建议您也将User.php模型中的函数重命名gender为genders我看到您gender_id在创建用户时使用:$user = User::create([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'genders_id' => $genders,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'name' => $data['name'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'email' => $data['email'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'age' => $data['age'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'password' => Hash::make($data['password']),]);这实际上不起作用,因为 Laravel 将gender_id在表中搜索如果你想保留 genders_id,你可以hasMany这样设置: return $this->hasMany(User::class, 'genders_id');
打开App,查看更多内容
随时随地看视频慕课网APP