Laravel没有将数据插入一对多关系

时间:2019-10-23 16:47:02

标签: php laravel eloquent

我有两张桌子的学生和科目,并且存在一对多的关系,因为一个科目可以包含许多学生。一个学生只能包含一个主题。但是在我的数据库中,正在插入数据(主题ID除外)。 我的student.php

protected $fillable=['name','username','password','interest','email','gender','image'];
public function subject()
    {
        return $this->belongsTo(Subject::class);
    }

Subject.php

protected $fillable=['name','department_id'];
 public function students()
    {
        return $this->hasMany(Student::class,'interest');
    }

这是我的播种机

public function run()
    {
        $subject = new Subject;
        $subject->name="Software";
        $subject->save();
        $student=Student::create([
                'name' =>  Str::random(6),
                'email' =>  Str::random(6).'@gmail.com',
                'username' => Str::random(6),
                'password' => bcrypt('tanvir'),
                'phone' =>  rand(),
                'gender' => Str::random(6),
                'image' => bcrypt('tanvir'),
            ]);
        $student->subject()->associate($subject);
    }

这是我的迁移文件

Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('username')->unique();
            $table->string('password')->unique();
            $table->string('phone');
            $table->unsignedBigInteger('interest')->nullable();
            $table->string('gender');
            $table->string('image')->nullable();
            $table->timestamps();
            $table->foreign('interest')
                ->references('id')->on('subjects')
                ->onDelete('cascade')
                ->onUpdate('cascade');
        });
Schema::create('subjects', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('department_id')->nullable();
            $table->string('name');
            $table->timestamps();

            $table->foreign('department_id')
                ->references('id')->on('departments')
                ->onDelete('cascade')
                ->onUpdate('cascade');
        });

数据库播种正常,但科目ID未保存在兴趣列的学生表中。请帮助我解决问题。

1 个答案:

答案 0 :(得分:0)

因为您未遵循约定,所以我认为Laravel不知道如何将用户与主题联系起来。所以您可以尝试以下操作:

public function subject()
{
    return $this->belongsTo(Subject::class, 'interest');
}

Laravel期望外键是subject_id,但是它是interest,因此您需要告知Laravel。

编辑

$student = Student::create([
   'name' =>  Str::random(6),
   'email' =>  Str::random(6).'@gmail.com',
   'username' => Str::random(6),
   'password' => bcrypt('tanvir'),
   'phone' =>  rand(),
   'gender' => Str::random(6),
   'image' => bcrypt('tanvir'),
   'interest' => $subject->id
]);