composer创建Laravel应用已经有博文了,在此不重复。
首先创建一个数据库,这里用MySQL:
在.env文件中添加数据库相关信息:
B_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_test
DB_USERNAME=root
DB_PASSWORD=root
创建Products模型
php artisan make:model Products -m
在Models下会自动创建Products.php文件以及migrations下会创建对应的迁移文件。
在迁移文件中新建字段
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->double('price');
$table->longText('description');
$table->timestamps();
});
}
然后在model中进行对应
class Products extends Model
{
use HasFactory;
protected $fillable = [
'name', 'price', 'description'
];
}
运行迁移文件
php artisan migrate
这样表就创建好了,下面生成仿真数据。
在ProductsFactory.php中新增definition的return值
public function definition()
{
return [
'name' => $this->faker->word,
'price' => $this->faker->numberBetween(1, 99),
'description' => $this->faker->sentence()
];
}
最后在DatabaseSeeder.php中进行创建
public function run()
{
// \App\Models\User::factory(10)->create();
Products::factory(20)->create();
}
最终执行命令生成仿真数据
php artisan db:seed
数据库中就有数据了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)