欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

Laravel 5.2中关于.env文件与模型操作的实例分享

程序员文章站 2022-04-02 11:03:15
...

一、 .env 文件

.env 文件是应用的环境配置文件,在配置应用参数、数据库连接、缓存处理时都会使用这个文件。


// 应用相关参数
APP_ENV=local
APP_DEBUG=true   //应用调试模式
APP_KEY=base64:hMYz0BMJDJARKgrmaV93YQY/p9SatnV8m0kT4LVJR5w= //应用key
APP_URL=http://localhost
// 数据库连接参数
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelblog
DB_USERNAME=root
DB_PASSWORD=
DB_PREFIX='hd_'

// 缓存相关参数
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

// Redis 连接参数
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

// 邮件相关参数
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null  

其中,有关这个 APP_KEY 的解释,在 config/app.php 文件中有如下注释:


/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',

key 键读取 .env 文件的 APP_KEY ,一般是 32 位的随机字符串。cipher 键决定 APP_KEY 的长度,一般是 AES-256-CBC (默认)表示 key 长 32 位字符,或者 AES-128-CBC 表示 16 位。

所以,为了保证会话和加密服务的安全, APP_KEY 必须设置,使用 Artisan 命令生成:


php artisan key:generate

这样,.env 文件中就会写入一个新的 APP_KEY

二、模型操作

1. DB 类


// 插入
DB::insert('insert into hd_user(username, password) values(?, ?)', ['admin', 123456]);

// 查询
DB::select('select * from hd_user where username = ?', ['admin']);

// 更新
DB::update('update hd_user set password= ? where username = ?', [654321, 'admin']);

// 删除
DB::delete('delete from hd_user where username = ?', ['admin']);

注:dd() 函数类似print_r(), 用于打印变量信息,是 Laravel 的辅助函数。

2. 查询构建器

DB 类的 table 方法为给定表返回一个查询构建器。


// 查询所有
DB::table('user')->get();

// 查询多条
DB::table('user')->where('age', '>', 20)->get();

// 查询一条
DB::table('user')->where('age', '>', 20)->first();

// 查询特定字段
DB::table('user')->select('name', 'email as user_email')->get();

// distinct() 方法去重复
$users = DB::table('user')->distinct()->get();

  

3. Eloquent ORM

1.创建模型


php artisan make:model User

2. 表名、主键、时间戳

表名:默认模型类名的复数作为表名,可以在模型类中定义 protected $table 属性来覆盖。

主键:默认主键名为"id",可以在模型类中定义 protected $primaryKey 属性来覆盖。

时间戳:默认会管理 created_at 和 updated_a 字段,可以在模型类中定义 public $timestamps 属性为 false 。

Laravel 5.2中关于.env文件与模型操作的实例分享

3.数据操作

在控制器方法中:


// 插入
$user = new User;
$user->username = 'admin';
$user->save();
// 查询
// 查询所有
User::get();

// 查询多条
User::where('age', '>', '20')->get();

// 查询一条
user::find(1);


// 更新
$user = User::find(1); // 查找主键为1的一条记录
$user->username = 'new name';
$user->save();         // 或者用 update() 方法


// 删除

// 方法1.先获取记录再删除
User::find(1)->delete();

// 方法2.通过主键直接删除
User::destroy(1, 2);

// 方法3.通过 where 条件删除
User::where('username', 'admin')->delete();

以上就是Laravel 5.2中关于.env文件与模型操作的实例分享的详细内容,更多请关注其它相关文章!