如何在Laravel的其他字段中用伪造的值播种数据透视表数据库?

时间:2019-03-29 09:49:15

标签: laravel pivot factory seed faker

我想用伪造的值播种我的数据库。我有4个数据库表:User,Order,Products和Order_Products。最后一个表是订单和产品之间的数据透视表。我在此数据透视表中添加了两个字段:金额和价格。现在我想用伪造者数据填充所有这些表。如果我将两个额外的字段留在后面,则可以使用下面的代码。如果我在迁移中添加两个额外的字段。我收到一个错误(显而易见)。但是,如何填写数据透视表中的其他字段?预先感谢。

在我的数据透视表中没有多余字段的情况下,它可以正常工作,但是知道我也希望用伪造数据填充额外字段。

工厂订单

$factory->define(App\Order::class, function (Faker $faker) {
    return [
        'orderdate' => now(),
        'amount' => $faker->randomFloat(2,0,6)
    ];
});

工厂产品

$factory->define(App\Product::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'description' => $faker->sentence(),
        'price'=> $faker->randomFloat(2,0,6)
    ];
});

种子

public function run()
{
   factory(App\User::class, 5)->create()->each(function ($user) {
            $user->orders()
                 ->saveMany(factory(App\Order::class, 2)
                 ->create(['user_id' => $user->id])
                 ->each(function ($order){
                      $order->products()
                      ->saveMany(factory(App\Product::class, 3)
                      ->create());
                      })
                      );
            });
}

迁移数据透视表

public function up()
{
    Schema::create('order_product', function (Blueprint $table) {
        $table->unsignedBigInteger('order_id');      
        $table->unsignedBigInteger('product_id');
        $table->integer('amount');
        $table->float('price',8,2);
    });

    Schema::table('order_product', function($table) {
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
        $table->primary(['order_id', 'product_id']);
    });
}

1 个答案:

答案 0 :(得分:1)

尝试一下

 public function run ()
 {
  factory ( App\User::class, 5 )->create ()
     ->each ( function ( $user ) {
        $user->orders ()->saveMany ( factory ( App\Order::class, 2 )->create ( [ 'user_id' => $user->id ] )
              ->each ( function ( $order ) {
                 $products = factory ( App\Product::class, 3 )->make ();
                 foreach ( $products as $product )
                 {
                    $order->products ()->attach ( $product->id, [ 'amount' => 'xxx', 'price' => 'xxx' ] );
                 }
              } )
           );
     } );

}