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
複製代碼