【问题标题】:Laravel save data from one form to different database tablesLaravel 将数据从一种形式保存到不同的数据库表中
【发布时间】:2020-04-14 18:25:30
【问题描述】:

我想创建一个有一些课程的学生。

This is the Laravel view

我创建了两个不同的表:一个学生表

public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('student_name');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email');
        });
    }

还有一个课程表。

public function up()
    {
        Schema::create('student_courses', function (Blueprint $table) {
            $table->id();
            $table->unsignedInteger('student_id');
            $table->string('course_name');
            $table->timestamps();
        });
    }

students表创建学生的信息,并保存在student表中。

我想用学生 ID 将课程保存到课程表中。他们应该有一对多的关系。如何使用特定学生的 id 将不同的课程保存到课程表中?

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    您不能将课程名称存储在学生课程表中。您需要为课程创建单独的表格。之后,您可以使用外键将学生和课程的数据存储到 student_courses 表中,如下所示。

    public function up()
    {
        Schema::create('student_courses', function (Blueprint $table) {
            $table->id();
            $table->integer('student_id')->unsigned()->nullable();
            $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
    
            $table->integer('course_id')->unsigned()->nullable();
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
            $table->timestamps();
        });
    }
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      首先创建关系: 在用户模型中创建: public function courses(){ return $this->hasMany(Course::class); }

      在课程模型中创建: public function students(){ return $this->belongsTo(Studnet::class); } 现在在您的保存功能中:

      $course = new Course($request->all());
      $user->courses()->save($course);
      

      【讨论】:

        猜你喜欢
        • 2017-12-20
        • 2020-06-09
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多