猿问

Laravel 创建具有相同列名的表

我尝试创建 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_atprocessing_ended_at

将来我想创建更多具有相同列名的表,也许我会创建所有表都需要的更多列。

所以我想知道最好的方法是让事情保持干净一点。每当我创建新的迁移文件时,有没有办法创建某种默认列?还是我应该建立关系?我还发现了一些关于多态关系的东西,但我不确定它是否适用于此


森栏
浏览 136回答 2
2回答

慕尼黑8549860

如果你的表中没有更复杂的依赖关系,我建议你使用多态关系。创建一个表:public function up(){    Schema::create('processes', function (BlueprintCustom $table) {        $table->morphs('process');        $this->timestamp('processing_started_at')->nullable();        $this->timestamp('processing_ended_at')->nullable();    });}并将您的关系添加到您的相关模型。这将缓解从同一领域到您的迁移。

小唯快跑啊

您可以创建一个继承自的自定义蓝图类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();    });}
随时随地看视频慕课网APP
我要回答