2016-11-27 81 views
0

我不想播种“一对多”的关系。播种/迁移有很多关系

产品型号

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

产品和订单之间的关系应该是many-to-many,你应该创建一个新表order_product与列:

id | order_id | product_id 

按照Laravel docs它会帮助你解决你的问题。如果你被困在任何地方,那么SO会帮助你。