2016-11-27 17 views
0

"One To Many"の関係を設定することはできません。シード/マイグレーディングhasMany関係

製品モデル

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に従ってください。あなたがどこにいてもあなたが助けてくれるならば。

関連する問題