我不想种下一对一的#34;关系。
产品型号
class Product extends Model
{
protected $table = 'products';
}
订单型号
class Order extends Model
{
protected $table = 'orders';
/**
* Products by order.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function comments()
{
return $this->hasMany('Product');
}
}
产品迁移
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->integer('stock');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
订单迁移
class CreateOrdersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
// refers to a user table
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users');
// "One To Many" relation???
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('orders');
}
}
产品播种机
class ProductsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('products')->insert([
'name' => 'EEE PC',
'stock' => 20
]);
}
}
订购播种机
class OrdersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('orders')->insert([
'user_id' => 1
// "One To Many" relation???
]);
}
}
我是否需要创建一个类似" order_product"的连接表?或者其他的东西?我感到困惑,因为在订单模型中,hasMany
指的是产品
订单包含产品,但每种产品都可以按不同的顺序使用!
答案 0 :(得分:0)
产品和订单之间的关系应为many-to-many
,您应该创建一个包含列的新表order_product
:
id | order_id | product_id
按照Laravel docs,它将帮助您解决问题。如果你被困在任何地方,那么SO可以帮助你。