二刷Laravel 教程(用户模型)总结Ⅲ

一、数据库迁移

当我们运行迁移时,up 方法会被调用;(创建表)
当我们回滚迁移时,down 方法会被调用。(删除表)

public function up ()

{

//create 方法会接收两个参数:一个是数据表的名称,另一个则是接收 $table(Blueprint 实例)的闭包。

Schema::create ('users', function (Blueprint $table) {

$table->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 cache:clear

php artisan config:clear

php artisan migrate

二、查看数据库表

三、模型文件

1)用户模型中定义的三个属性

$casts(指定数据库字段使用的数据类型)

fillable(过滤用户提交的字段,只有包含在该属性中的字段才能够被正常更新。避免『批量赋值』的错误) hidden(用户密码或其它敏感信息在用户实例通过数组或 JSON 显示时进行隐藏)

2)创建文章模型(Article)为例

>>>只创建模型(模型类名称使用 单数 形式来命名)

php artisan make:model Article
//删除模型

rm app/Models/Article.php

>>>创建模型的同时创建数据迁移

php artisan make:model Article -m

3)Eloquent表命名约定

「下划线命名法」与「复数形式名称」来作为数据表的名称生成规则

Article 数据模型类对应 articles 表;
User 数据模型类对应 users 表;
BlogPost 数据模型类对应 blog_posts 表;

四、创建用户对象

进入Tinker环境:

php artisan tinker

在Tinker里面创建一个用户对象:

//调用了一个叫bcrypt 的方法,将 password 的值进行加密

App\Models\User::create(['name'=> 'Summer', 'email'=>'summer@example.com','password'=>bcrypt('password')])

五、查找用户对象

使用 use 来引用 App\Models\User Eloquent 模型类

use App\Models\User

六、更新用户对象(两种方法)

第一种是通过给用户对象属性进行赋值,赋值成功后再调用 save 方法进行保存更新;

1.$user = User::first()

2.$user->name = 'Monkey'

3.$user->save() //保存,不保存显示的还是未修改之前的

4.User::first()

第二种则是直接调用 update 方法进行更新。(这个嘎嘎好,比第一个)

1.$user->update(['name'=>'Summer'])

2.User::first()

相关推荐
BingoGo16 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack16 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
BingoGo4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·laravel
JaguarJack4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
QQ5110082854 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php