我正在创建一个表,我想使用这个表的ID "menu_item "要添加到另一个表
表一:menu_itemsSchema::create('menu_items', function (Blueprint $table) {
$table->id('menu_level_item_id');
$table->timestamps();
$table->string('menu_item_name');
$table->string('menu_item_desc');
表2产品
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_desc');
$table->integer('price');
$table->integer('menu_level_item_id');
$table->timestamps();
});
我这样做的目的是,我可以在两个表之间创建一个关系,因为它们具有相同的键?
我可以采取不同的方法吗?我应该在创建菜单项时创建唯一键,然后将其添加到第二个表中吗?
谢谢。
基本上Laravel Eloquent做键处理。当您有两个表,它们都以名称id作为键时,这不是问题。像这样命名关系表中的键
table1_id
table2_id
Laravel将在Eloquent中处理此问题。您还可以将关系表中的两列命名为您想要的任何名称。您可以在Eloquent中为关系定义它。例如
public function otherModel () {
return $this->belongsToMany('AppModelsOtherModel', 'table_name', 'this_model_id', 'other_model_id');
}
请看:Laravel关系文档
Schema::create('menu_items', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('menu_item_name');
$table->string('menu_item_desc');
table->timestamp();
});
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_desc');
$table->integer('price');
$table->unsignedBigInteger('menu_level_item_id');
$table->timestamps();
$table->foreign('menu_level_item_id')->references('id')->on('menu_items');
});