Laravel 自带的 Seeder ,可以批量生成一些假数据对页面填充。节约了手动填充假数据的时间。本小节介绍一下利用 Seeder 来生成30条商品数据信息和每条商品对应的3条sku信息。

    生成对应的工厂文件
// 商品
>$ php artisan make:factory ProductFactory --model=Models\Product
// 商品 sku
>$ php artisan make:factory ProductSkuFactory --model=Models\ProductSku

ProductFactory.php

<?php
use Faker\Generator as Faker;

$factory->define(App\Models\Product::class, function (Faker $faker) {
$image = $faker->randomElement([
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/7kG1HekGK6.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/1B3n0ATKrn.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/r3BNRe4zXG.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/C0bVuKB2nt.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/82Wf2sg8gM.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/nIvBAQO5Pj.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/XrtIwzrxj7.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/uYEHCJ1oRp.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/2JMRaFwRpo.jpg",
"https://iocaffcdn.phphub.org/uploads/images/201806/01/5320/pa7DrV43Mw.jpg",
]);
return [
'title' => $faker->word,
'description' => $faker->sentence,
'image' => $image,
'on_sale' => true,
'rating' => $faker->numberBetween(0,5),
'sold_count' => 0,
'review_count' => 0,
'price' => 0,
];
});

$faker->randomElement: 随机取数据;$faker->word: 随机获取一个内置的单词。

ProductSkuFactory.php 

<?php
use Faker\Generator as Faker;

$factory->define(App\Models\ProductSku::class, function (Faker $faker) {
return [
'title' => $faker->word,
'description' => $faker->sentence,
'price' => $faker->randomNumber(4),
'stock' => $faker->randomNumber(5),
];
});
    创建 Seeder 文件 批量生成数据
>$ php artisan make:seed --class=ProductsSeeder
<?php
use Illuminate\Database\Seeder;

class ProductsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// 创建 30 个商品
$products = factory(\App\Models\Product::class, 30)->create();

// 给每个商品创建 3 个 SKU
foreach ( $products as $product ) {
// 每个 SKU 的 `product_id` 都设为当前循环的商品 id
$skus = factory(\App\Models\ProductSku::class, 3)->create(['product_id'=>$product->id]);

// 找出价格最低的 SKU 价格,把商品价格设置成该价格
$product->update(['price'=>$skus->min('price')]);
}
}
}
    运行 Seeder 文件
>$ php artisan db:seed --class=ProductsSeeder

这时,30条假商品数据和每条商品对应的3条 SKU 数据已经插入到数据库中了。

下面用命令行 tinker 来演示一下创建商品信息的假数据,如何根据创建好的商品数据来创建 SKU 数据,现在还不清楚,等知道了在回来补充,也希望知道的大神在评论区里讨论下,谢谢!

    进入命令行交互界面
>$ php artisan tinker
>>> namespace
...App\Models
>>> factory(Product::class, 30)->create();

namespace 指定命名空间。

至此,利用 Seeder 和 tinker 两种方法生成假数据的方法,简单的介绍了一遍,个人更偏向于 Seeder 因为可以迁移,只要远行 php artisan db:seeder ProductsSeeder 即可。

由于能力有限,不足或有不解之处,希望在下方评论区与我讨论,共同提高 。