【发布时间】:2018-01-31 03:00:09
【问题描述】:
我有 3 个表,我正在尝试在 order_products 和 order_products_status_names 之间建立关系。我有名为 order_product_statuses 的转换/数据透视表。问题是我的 PK,因为我有表订单 3 Pk,我不知道如何通过关系连接这 3 个表。 我的迁移是:
餐桌订购产品:
public function up()
{
Schema::create('order_products', function (Blueprint $table) {
$table->integer('order_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('ordinal')->unsigned();
$table->integer('size');
$table->primary(['order_id', 'product_id', 'ordinal']);
$table->foreign('order_id')->references('id')->on('orders');
$table->foreign('product_id')->references('id')->on('products');
});
}
表格订单产品状态 - 这是我在 order_products 和 order_product_status_names 之间的转换/数据透视表
public function up()
{
Schema::create('order_product_statuses', function (Blueprint $table) {
$table->integer('order_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('status_id')->unsigned();
$table->integer('ordinal')->unsigned();
$table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->foreign('order_id')->references('id')->on('orders');
$table->foreign('status_id')->references('id')->on('order_product_status_names');
$table->primary(['order_id', 'product_id', 'ordinal']);
});
}
最后一个是订单产品状态名称
public function up()
{
Schema::create('order_product_status_names', function (Blueprint $table) {
$table->integer('id')->unsigned();
$table->string('name');
$table->string('code');
$table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->primary('id');
});
}
我知道这里有两种关系 blengsToMany,但我不知道或者我可以声明这种关系(从 order_products 到 order_product_status_names 和 inverse )?
【问题讨论】:
-
明天早上会仔细看看你的需求,看看能不能帮到你。
-
只是一个简单的问题,为什么您在 order_product 和 order_product_statuses 中都有 order_id 和 product_id,这是出于性能原因吗?
-
谢谢!我会等待并感谢它!
-
Eloquent 确实不是为复合键设计的。通过使您的数据库结构符合每个表中的
id主键,您将省去很多麻烦。 -
是的,因为我有 3 个 PK(order_id、product_id 和普通),当客户订购 2 个相同尺寸的相同产品时,我有 2 个不同的行,只有序数可以将它们与 1 区分开命令。当客户只从他们那里拿走一个时,我可以添加单独的状态
标签: php laravel relationship composite-primary-key