【问题标题】:Create a pivot migration with extra columns in laravel在 laravel 中创建带有额外列的数据透视迁移
【发布时间】:2018-01-28 04:23:39
【问题描述】:

我读过这个 https://laravel.com/docs/5.4/eloquent-relationships#many-to-many 我发现

php artisan migrate

不会自动创建数据透视表,我检查了应该如何创建它,但我不知道如何使用额外的列创建它。 例如,这些是我的相关模型:

class User extends Authenticatable {
  public function courses() 
  {
    return $this->belongsToMany('App\Course')
    ->withPivot('attendance', 'grade');
      ->withTimestamps();
  }
}

另一个模型

class Course extends Model
{
//
}

在这里我不需要反比关系来实例化。

问题是当我转到 mysql 时,我找不到数据透视表。那么如何使用这些数据透视列手动创建它。

【问题讨论】:

  • 创建迁移。基本迁移规则在这里laravel.com/docs/5.4/migrations
  • @Bharat Geleda 我在发布问题之前阅读了这个帖子。我需要指定问题中未提及的额外列。尽管他的第二个答案可能对我有用。但是我没有从这个角度去看。我回来后会试试的。
  • 是的,关于在数据透视表中添加额外列的文档都没有提到在迁移文件中添加属性。然而,这是隐含的假设。数据库中的任何重大更改都是单独使用迁移文件执行的。 Eloquent ORM 模型更上一层楼。

标签: php mysql laravel laravel-5.4


【解决方案1】:

您必须使用如下迁移手动创建中间/数据透视表(您必须按字母顺序命名您的表):

    public function up()
    {
        Schema::create('course_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('course_id')->unsigned();
            $table->foreign('course_id')->references('id')->on('courses');
            $table->string('attendance');
            $table->string('grade');
            $table->timestamps();
        });
    }

之后,运行迁移:

php artisan migrate

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 2016-05-10
    • 2017-09-04
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多