配置

  1. config/database.php
  2. .env 文件
  3. env($key, $default = null), 表示如果 .env 文件中该 $key 设置了值就用此值,如果没有就用 $default 值
  4. .env 只适用本地开发,不放到版本库和线上服务器
  5. 即本地用 .env , 线上用 database.php 文件

config/database.php 中包含很多类型的数据库连接驱动,这保证了开箱即用,通常你可以修改或者删除它们,根据你的需要。

但是有时,在一个应用中也可能会用到多个连接驱动,例如你对两种不同类型的数据使用不同的数据库,或者你要实现读写分离等。laravel支持多连接。

其他的配置

config/database.php 中还包含一些其余配置,redis 连接,自定义迁移的表名字,默认的数据库连接,切换非 Eloquent 调用时返回对象还是数组(?)。

Laravel中的任何服务都允许来自多个源的连接。 sesssion 可以由数据库或文件存储支持,缓存可以使用Redis或Memcached,数据库可以使用MySQL或PostgreSQL, 您可以定义多个连接,还可以选择使用特定连接或将某个连接设为“默认”, 如果需要,请按以下方法请求特定的连接:

  1. $users = DB::connection('secondary')->select('select * from users');

[role=”less_space pagebreak-before”]’ === Migrations

迁移

迁移是一个独立的文件,定义了两件事,up 向上迁移的操作(前进),down 向下迁移的操作(回滚)。

迁移总是按时间排序,迁移文件的名字就像 2018_10_12_000000_create_users_table.php , 迁移新系统后,系统会从最早的日期开始抓取每次迁移,然后运行其 up() 方法-此时您将“向上”迁移。 但是,迁移系统还允许您“回滚”最新的迁移集。 它将抓住并运行它们中的每一个 down() 方法,该方法应撤消对向上迁移所做的任何更改。

创建迁移

laravel 的 artisan 可以创建迁移,如下:

  1. php artisan make:migration create_users_table
  2. php artisan make:migration create_users_table --create=users // 创建表
  3. php artisan make:migration add_votes_to_users_table --table=users // 修改表

artisan make:migration 命令会根据名字来决定是创建还是修改表,如果你遵循一定规范的话。

创建表

  1. Schema::create('users', function (Blueprint $table) {
  2. // Create columns here
  3. });

创建字段

  1. Schema::create('users', function (Blueprint $table) {
  2. $table->string('name');
  3. });

字段类型

  • integer(colName) , tinyInteger(colName) , smallInteger(colName) ,mediumInteger(colName) , bigInteger(colName)

Adds an INTEGER type column, or one of its many variations

  • string(colName, length)

Adds a VARCHAR type column with an optional length

  • binary(colName)

Adds a BLOB type column

  • boolean(colName)

Adds a BOOLEAN type column (a TINYINT(1) in MySQL)

  • char(colName, length)

Adds a CHAR column with an optional length

  • datetime(colName)

Adds a DATETIME column

  • decimal(colName, precision, scale)

Adds a DECIMAL column, with precision and scale—for example, decimal(‘amount’, 5, 2) specifies a precision of 5 and a scale of 2

  • double(colName, total digits, digits after decimal)

Adds a DOUBLE column—for example, double(‘tolerance’, 12, 8) specifies 12digits long, with 8 of those digits to the right of the decimal place, as in 7204.05691739

  • enum(colName, [choiceOne, choiceTwo])

Adds an ENUM column, with provided choices

  • float(colName, precision, scale)

Adds a FLOAT column (same as double in MySQL)

  • json(colName) and jsonb(colName)

Adds a JSON or JSONB column (or a TEXT column in Laravel 5.1)

  • text(colName) , mediumText(colName) , longText(colName)

Adds a TEXT column (or its various sizes)

  • time(colName)

Adds a TIME column

  • timestamp(colName)

Adds a TIMESTAMP column

  • uuid(colName)

Adds a UUID column ( CHAR(36) in MySQL)And these are the special (joined) Blueprint methods:increments(colName) and bigIncrements(colName) Add an unsigned incrementing INTEGER or BIG INTEGER primary key ID

  • timestamps() and nullableTimestamps()

Adds created_at and updated_at timestamp columns

  • rememberToken()

Adds a remember_token column ( VARCHAR(100) ) for user “remember me” tokens

  • softDeletes()

Adds a deleted_at timestamp for use with soft deletes

  • morphs(colName)

For a provided colName , adds an integer colName_id and a string colName_type (e.g., morphs(tag) adds integer tag_id and string tag_type ); for use in polymorphic(多态) relationships

额外的属性

  1. // 在 last_name 字段后 新增 email 字段,且允许为null
  2. Schema::table('users', function (Blueprint $table) {
  3. $table->string('email')->nullable()->after('last_name');
  4. });

下面是一些额外属性

  • nullable()

Allows NULL values to be inserted into this column

  • default(‘default content’)

Specifies the default content for this column if no value is provided

  • unsigned()

Marks integer columns as unsigned (not negative or positive, but just an integer)

  • first() (MySQL only)

Places the column first in the column order

  • after(colName) (MySQL only)

Places the column after another column in the column order

  • unique()

Adds a UNIQUE index

  • primary()

Adds a primary key index

  • index()

Adds a basic index

删除表

  1. Schema::dropIfExists('contacts');

修改字段

编写和创建字段一样的代码,在后边加上 change() 方法即可

  1. // 修改字段长度
  2. Schema::table('users', function (Blueprint $table) {
  3. $table->string('name', 100)->change();
  4. });
  5. // 修改可空
  6. Schema::table('contacts', function (Blueprint $table) {
  7. $table->string('deleted_at')->nullable()->change();
  8. });
  9. // 修改字段名
  10. Schema::table('contacts', function (Blueprint $table){
  11. $table->renameColumn('promoted', 'is_promoted');
  12. });
  13. // 删除字段
  14. Schema::table('contacts', function(Blueprint $table){
  15. $table->dropColumn('vote');
  16. });

tip1: SQLite 类型的数据库,修改或删除字段前要安装依赖 composer require doctrine/dbal

tip2: SQLite 中一个迁移闭包中修改或删除多个字段,会出错,请按如下操作(一次迁移中多次调用 ::table() 方法):

  1. public function up()
  2. {
  3. Schema::table('contacts', function (Blueprint $table){
  4. $table->dropColumn('is_promoted');
  5. });
  6. Schema::table('contacts', function (Blueprint $table){
  7. $table->dropColumn('alternate_email');
  8. });
  9. }

索引与外键

添加索引

  1. // After columns are created...
  2. $table->primary('primary_id'); // Primary key; unnecessary if used increments()
  3. $table->primary(['first_name', 'last_name']); // Composite keys
  4. $table->unique('email'); // Unique index
  5. $table->unique('email', 'optional_custom_index_name'); // Unique index
  6. $table->index('amount'); // Basic index
  7. $table->index('amount', 'optional_custom_index_name'); // Basic index

删除索引

  1. $table->dropPrimary('contacts_id_primary');
  2. $table->dropUnique('contacts_email_unique');
  3. $table->dropIndex('optional_custom_index_name');
  4. // If you pass an array of column names to dropIndex, it will
  5. // guess the index names for you based on the generation rules
  6. $table->dropIndex(['email', 'amount']);

添加外键

  1. $table->foreign('user_id')->references('id')->on('users');
  2. // 有外键约束的 onDelete onUpdate
  3. $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

删除外键

  1. // 指定外键名 contacts_ + 列名 + _foreign 自动生成
  2. $table->dropForeign('contacts_user_id_foreign');
  3. // 直接传递本表中的字段名数组
  4. $table->dropForeign(['user_id']);

运行迁移

php artisan migrate

此命令运行所有“未执行”的迁移(通过运行每个迁移的 up() 方法)。 Laravel 会跟踪哪些迁移已运行哪些未运行。每次运行此命令时,它都会检查所有迁移,并找出未运行的运行它们。

一些参数

  • migrate:install

创建数据表跟踪迁移是否允许,自动运行,忽略它

  • migrate:reset

回滚所有你已经执行的迁移

  • migrate:refresh

回滚你已经执行的迁移,然后执行所有可用迁移,相当于 先执行 migrate:reset 然后执行 migrate

  • migrate:fresh

删除所有数据表,然后执行所有可用迁移,和 refresh 效果一样,只不过,这里是删除表, refresh 是执行 down() 方法

  • migrate:rollback

回滚最后一次迁移,或加参数 --step=n 指定回滚次数

  • migrate:status

显示一个表包含每个迁移的执行状态