【问题标题】:Seeding/migrating hasMany relation播种/迁移 hasMany 关系
【发布时间】: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


    【解决方案1】:

    产品和订单之间的关系应该是many-to-many,您应该创建一个新表order_product,其中包含列:

    id | order_id | product_id
    

    关注 Laravel docs 它将帮助您解决问题。如果您被困在任何地方,那么 SO 可以为您提供帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-07
      • 2014-08-14
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2018-06-21
      相关资源
      最近更新 更多