database/migrations/
php
php artisan make:migration create_users_table
复制代码
class CreateFlightsTable extends Migration
{
/**
* 用于添加新的数据表, 字段或者索引到数据库
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* 用于删除数据表, 字段或者索引到数据库
*/
public function down()
{
Schema::dropIfExists('users');
}
}
复制代码
php artisan make:migration add_votes_to_users_table --table=users
复制代码
public function up()
{
Schema::table('goods', function (Blueprint $table) {
$table->string('name');//添加name字段
});
}
public function down()
{
Schema::table('goods', function (Blueprint $table) {
$table->dropColumn('name');//删除字段
});
}
复制代码
php artisan migrate
复制代码
database/seeds/
mysql
php artisan make:seeder UsersTableSeeder
复制代码
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'name' => Str::random(10),
'email' => Str::random(10).'@gmail.com',
'password' => bcrypt('secret'),
]);
}
}
复制代码
/app/Models/
sql
php artisan make:model Models/User
复制代码
database/factories/
docker
php artisan make:factory UsersFactory
复制代码
# Faker是一个开源类库,主要用于生成一些测试数据,好比电话号码,人名,IP地址等等
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
复制代码
database/seeds/UsersTableSeeder.php
数据库
public function run()
{
//生成10条数据
factory(User::class)->times(10)->create();
}
复制代码
php artisan db:seed --class=UsersTableSeeder
复制代码
参考文章bash
Eloquent 将会使用所属模型名称的 『snake case』形式,再加上 _id 后缀做为外键字段。例如,Eloquent 将假定 Comment 对应到 Post 模型上的外键就是 post_id。app
hasMany(关联模型的类名, 关联模型的外键, 当前模型主键)
dom
# 关联表SsqPrize
public function ssqPrize()
{
return $this->hasMany(SsqPrize::class);
}
public function getSsqHistroy()
{
return Ssq::with('ssqPrize')->get();
}
复制代码
belongsToMany(关联模型的类名, 中间表的表名, 当前表在中间表里的键,关联表在中间表里的键)
socket
# 当前表contact,关联表appointment,中间表bl_appointment_rel
public function appointment()
{
return $this->belongsToMany('App\Models\AppointmentModel', 'bl_appointment_rel',
'account_id', 'appointment_id')
->where('bl_appointment_rel.account_type', 2);
}
复制代码
查询post
$data = ContactsModel::with('appointment')
->where('id', $contactId)
->whereHas('appointment', function ($query) use ($date) {
$query->whereDate('appointment_time', $date);
})
->get();
复制代码
SQLSTATE[HY000] [2002] No such file or directory
复制代码
解决
问题是由于config/database.php中unix_socket参数须要配置mysqld.sock
因此须要将mysql容器中的mysqld.sock挂载到本地,修改docker-compose.yml
volumes:
- ./docker/mysql/socket:/var/run/mysqld
复制代码
修改env配置文件,配置unix_socket
DB_SOCKET=../docker/mysql/socket/mysqld.sock
复制代码