如何在Laravel中为两个或多个表ID创建相同的foriegn_key

时间:2019-04-16 14:55:41

标签: laravel foreign-keys

在我的项目中,我有日记帐表,月度表,贷款表,投资表。日记帐表具有payment_id,我想为每月,贷款和投资表ID提供外键。我已经尝试过了,但是在迁移过程中会发生错误“在写入或更新时出现重复密钥”

我想做的是,当创建贷款,投资,月度时,我试图在日记表pay_id上插入贷款,投资,月度ID。我只能在日记表Payment_id上插入一个表ID(通过迁移中的外键关系),不能多个...我该怎么做?

public function up()
{
    Schema::create('journals', function (Blueprint $table) {
        $table->increments('id');
        $table->double('amount');
        $table->integer('payment_id')->unsigned();
        $table->enum('payment_format', ['monthly', 'investment', 'loan', 'income', 'expense', 'others']);
        $table->string('short_description');
        $table->integer('created_by')->unsigned();
        $table->integer('updated_by')->unsigned();
        $table->dateTime('deleted_at');
        $table->timestamps();

        $table->foreign('payment_id')->references('id')->on('monthlies')
            ->onUpdate('cascade')->onDelete('cascade');

        $table->foreign('payment_id')->references('id')->on('investments')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('payment_id')->references('id')->on('loans')
            ->onUpdate('cascade')->onDelete('cascade');

        $table->foreign('created_by')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('updated_by')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');

    });
}

1 个答案:

答案 0 :(得分:0)

您不能在laravel中做到这一点。同一列不能用作其他3个表的外键。但是,您可以在Laravel中执行此操作,而无需在数据库级别使用外键。

您的迁移:

download

在您的Schema::create('journals', function (Blueprint $table) { $table->increments('id'); $table->double('amount'); $table->integer('payment_id')->unsigned(); $table->enum('payment_format', ['monthly','investment','loan','income','expense','others']); $table->string('short_description'); $table->integer('created_by')->unsigned(); $table->integer('updated_by')->unsigned(); $table->dateTime('deleted_at'); $table->timestamps(); $table->foreign('created_by')->references('id')->on('users') ->onUpdate('cascade')->onDelete('cascade'); $table->foreign('updated_by')->references('id')->on('users') ->onUpdate('cascade')->onDelete('cascade'); }); 模型中,定义与付款的关系:

Journal

现在,通过调用public function payment() { switch($this->payment_format) { case 'loan': return $this->belongsTo(Loan::class, 'payment_id'); case 'monthly': return $this->belongsTo(Monthly::class, 'payment_id'); case 'investment': return $this->belongsTo(Investment::class, 'payment_id'); default: // ?? break; } } ,您将根据$journal->payment字段中的值获得正确的对象。