【发布时间】:2017-04-11 00:03:31
【问题描述】:
我不想播种“一对多”关系。
产品型号
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 指的是 Product
一个订单有产品,但每个产品可以在不同的订单中使用!
【问题讨论】:
标签: php laravel eloquent relationship one-to-many