Laravel- 使用migration 创建数据库

东郭元魁
2023-12-01

-- 文章仅供个人学习参考,如有不恰当的地方,希望前辈们指教。--

1、使用命令 创建数据库文件

php artisan make:model --migration Model/Posts
php artisan make:model --migration Model/Users

2、修改database\migrations 文件夹下会自动生成数据库文件

class CreatePostsTable extends Migration
{
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('uid'); // 是否含有附件
        $table->string('slug')->unique();
        $table->string('title')->null();
        $table->string('subject')->default('');
        $table->string('keywords')->default('');
        $table->integer('catalogue')->default(0);
        $table->integer('attach')->default(0); // 是否含有附件
        $table->timestamps();
        $table->timestamp('published_at')->index(); //正式发布时间
    });
  }
}

3、执行命令迁徙数据库

php artisan  migrate

4、修改App\Model\Posts.php

namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model {
    protected $datas = ['published_at'];

    //自动设置slug属性
    function setTitleAttribute($title) {
        $this->attributes['title'] = $title;
        if (!$this->exists) {
            $this->attributes['slug'] = str_slug($title);
        }
    }

}

5、填充测试数据

添加如下代码到 database/factories 目录下的 ModelFactory.php 文件中:

$factory->define(App\Model\Users::class, function (Faker\Generator $faker) {
      $admin=DB::table('users')->where('name','admin')->exists();
        if(!$admin){
            $create_at=$faker->dateTimeBetween('-1 month','+3 days');
              return [
               'name' => 'admin',
               'email' => 'admin@gmail.com',
               'password' => bcrypt('admin'), 
                'created_at'=> $create_at,
                'updated_at'=> $create_at,
            ]; 
        }
  
});
$factory->define(App\Model\Posts::class, function (Faker\Generator  $faker) {  
        $admin=DB::table('users')->where('name','admin')->first(); 
        if($admin){
            $id=$admin->id;
            $published_at=$faker->dateTimeBetween('-1 month','+3 days');
            $create_at=$faker->dateTimeBetween('-1 month',$published_at);
             return [
                'title' => $faker->sentence(mt_rand(3,10)), 
                'uid' => $id,
                'catalogue'=>1,
                'subject' => join('\n\n',$faker->paragraphs(mt_rand(3,6))),
                'created_at'=> $create_at,
                'updated_at'=> $create_at,
                'published_at' => $published_at
            ];
        }else{
            return [];
        } 
});

然后修改 database/seeds 目录下的 DatabaseSeeder.php 内容如下:

<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{ /**
  * Run the database seeds.
  */
  public function run()
  {
  	Model::unguard();
  	$this->call(UserTableSeeder::class);
  	$this->call(PostsTableSeeder::class);
  	Model::reguard();
  }
}
class PostsTableSeeder extends Seeder
{
  public function run(){
  	App\Model\Posts::truncate();
  	factory(App\Model\Posts::class,10)->create();
  }
}
class UsersTableSeeder extends Seeder
{
  public function run(){
  	App\Model\Users::truncate();
  	factory(App\Model\Users::class)->create();
  }
}

最后,在项目根目录下运行如下 Artisan 命令将随机数据插入数据库

composer dumpautoload
php artisan db:seed // 执行所有
php artisan db:seed --class=UsersTableSeeder // 单独执行一个

该命令执行成功后,posts 表中会多出10行记录,新增一个admin账户。

也可以使用 php artisan tinker 创建admin账户

[ciara@localhost blogtest]$  php artisan tinker
Psy Shell v0.7.2 (PHP 7.0.9 — cli) by Justin Hileman
>>> $user=new App\Model\Users;
=> App\Model\Users {#676}
>>> $user->name='admin'
=> "admin"
>>> $user->email='admin@qq.com'
=> "admin@qq.com"
>>> $user->password=bcrypt('111111');
=> "$2y$10$OtwSSCXeakwPjMwELHiOg.Lti3MG0HppGP.HislQjJ5A.QxfuRm2e"
>>> $user->save();
=> true
>>> exit;
Exit: Goodbye.


参考教程:http://laravelacademy.org/tutorials/blog
GitHub:  https://github.com/CiaraLi/blogtest




 类似资料: