2016-11-27 86 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會幫助你。