在一对多关系中,如何定义外键和本地键

时间:2019-07-03 11:53:11

标签: laravel laravel-5 eloquent eloquent--relationship

用户有很多注释。 笔记属于用户。

在用户模型中:

public function accountingNotes()
{
    return $this->hasMany(User::class,'user_id','user_id');
}

在注释模型中:

public function user()
{
    return $this->belongsTo(AccountingNote::class,'user_id','written_by');
}

用户迁移

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('user_id');
            // username will be used to login
            // authentication and validation are done to user username to login.
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->dateTime('first_login');
            $table->string('password', 60);
            $table->string('first_name');
            $table->string('last_name');
            $table->string('phone');
            $table->string('emergency_phone')->nullable();
            $table->enum('gender', ['male', 'female']);
            $table->string('profile_photo')->default('default.jpeg');
            $table->string('role');




            $table->rememberToken();
            $table->timestamps();
        });
    }

会计注释迁移

 public function up()
    {
        Schema::create('accounting_notes', function (Blueprint $table) {
            $table->bigIncrements('accounting_note_id');
            $table->text('content');
            $table->unsignedBigInteger('written_by');
            $table->foreign('written_by')->references('user_id')->on('users')->onDelete('CASCADE');
            $table->unsignedBigInteger('timesheet_id');
            $table->foreign('timesheet_id')->references('timesheet_id')->on('timesheets')->onDelete('CASCADE');

            $table->timestamps();
        });
    }

现在,用户已将user_id作为主键 在Note model中,written_by用于与用户建立联系。 我应该填写foreign key and local keys? 在许多博客中,他们的解释都是错误的,当我尝试几次时,它没有用,我来这里是为了寻求帮助。

谢谢

0 个答案:

没有答案