为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 创建具有相同列名的表

Laravel 创建具有相同列名的表

PHP
森栏 2023-04-15 17:47:11
我尝试创建 2 个表:Products - name - description - price - source - processing_started_at - processing_ended_at和Orders - customer_id - order_lines_id - source - processing_started_at - processing_ended_at如您所见,两个表都有以下列:source、processing_started_at和processing_ended_at将来我想创建更多具有相同列名的表,也许我会创建所有表都需要的更多列。所以我想知道最好的方法是让事情保持干净一点。每当我创建新的迁移文件时,有没有办法创建某种默认列?还是我应该建立关系?我还发现了一些关于多态关系的东西,但我不确定它是否适用于此
查看完整描述

2 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

如果你的表中没有更复杂的依赖关系,我建议你使用多态关系。创建一个表:


public function up()

{

    Schema::create('processes', function (BlueprintCustom $table) {

        $table->morphs('process');

        $this->timestamp('processing_started_at')->nullable();

        $this->timestamp('processing_ended_at')->nullable();

    });

}

并将您的关系添加到您的相关模型。这将缓解从同一领域到您的迁移。


查看完整回答
反对 回复 2023-04-15
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

您可以创建一个继承自的自定义蓝图类


Illuminate\Database\Schema\Blueprint

是这样的:


namespace App\Whatever;


use Illuminate\Database\Schema\Blueprint;


class BlueprintCustom extends Blueprint {

    public function customfields()

    {

        $this->string('source')->nullable();

        $this->timestamp('processing_started_at')->nullable();

        $this->timestamp('processing_ended_at')->nullable();

    }

}

那么,在迁移时,您可以执行以下操作:


use App\Whatever\BlueprintCustom;


public function up()

{

    Schema::create('newtable', function (BlueprintCustom $table) {

        $table->increments('id');

        $table->string('blah');

        $table->customfields();  //This adds your fields

        $table->timestamps();

    });

}


查看完整回答
反对 回复 2023-04-15
  • 2 回答
  • 0 关注
  • 124 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信