Laravel 模型的定义和使用

一.默认设置

1、框架可以使用 Eloquent ORM 进行数据库交互,也就是关系对象模型

在数据库入门阶段,我们已经创建了一个 User.php 模型,如下:

php artisan make:model Http/Models/User     //默认在 app 目录

2、而调用的时候,我们也知道表名要遵循它默认规则,修改为复数或者强制使用现有的数据表名

class User extends Model { 
    protected $table = 'user'; 
}

3、系统假定你的主键为 id,如果你要修改默认主键,可以设置:

protected $primaryKey = 'xid';

4、系统假定你的主键 id 为自增性,意味着是主键会自动转换 int 类型;

如果你希望不是非自增,非数值类型主键,可以设置取消

public $incrementing = false;

5、如果你主键不是一个整数,那么需要$keyType 设置为 string;

protected $keyType = 'string';

6、系统默认情况下会接管 created_at 和 updated_at 两个时间戳列;

如果不想让系统干涉这两个列,可以设置 false 取消;

public $timestamps = false;

7、如果你想自定义时间戳的格式,可以设置;

protected $dateFormat = 'U';

8、可以更改创建时间 created_at 和更新时间 updated_at 字段名;

const CREATED_AT = 'create_time'; 
const UPDATED_AT = 'update_time';

9、默认读取 database.php 配置的数据库连接,也可以在模型端局部更改

protected $connection = 'mysql';

二.模型定义

1、模型还是没有代码提示,可以通过安装插件解决:
composer require barryvdh/laravel-ide-helper

php artisan ide-helper:generate – 为 Facades 生成注释
php artisan ide-helper:models – 为数据模型生成注释
php artisan ide-helper:meta – 生成 PhpStorm Meta file

2、这里列出官网给出示例的方法,对照实验(结合详细文档,重复较多)

(1) .find(1) //通过主键查找 
(2) .first() //查找第一个 
(3) .firstWhere() //找到查询中的首个 
(4) .find([1,2,3]) //通过数组查找 
(5) .firstOr() //查找首个返回,支持闭包 
(6) .firstOrFail() //找不到时返回异常 
(7) .count()、max()等集合 //集合操作

3、我们要查询所有数据,直接使用模型::all()即可;

//查询所有记录 
$users = User::get(); //或 all() 
return [$users];

 三.模型的增删改

1、insert(新增)
$article = new Article();
$article->title="test1111";
$article->content="1111111";
$article->status='1';
$article->save();

create()方法实现新增:

$article = Article::create([
    'title'=>'test333', 
    'content'=>"333", 
    'status'=>1
]);


//通过提交过来的数据一次性新增
Article::create(Request::all());
一般情况下,是为了防止提交过来的字段在部分场景中不需要或不能,但需要在模型端设置批量赋值的许可:
protected $fillable = [
    'title',
    'content',
    'status'
];

//不许可的批量赋值,不可和$fillable 同时使用
//protected $guarded = ['uid'];
如果取消批量赋值限制,直接如下:
protected $guarded = [];
PS:必须在模型中定义批量赋值的可填充字段,否则无法生效;防止用户不小心设置新值;
PS:模型默认添加 created_at 和 updated_at 当前时间;

2、update(更新)

//修改单条
$article = Article::find(17);
$article->title="test2222";
$article->save();

//批量修改
$article = Article::where('title', 'test1') ->update([ 'title' => 'test' ]);

3、delete(删除)

//根据主键删除
$article = Article::find(17);
$article->delete();

//批量删除
$article = Article::where('title','test');
$article->delete();

//根据主键批量删除
Article::destroy([7,8]);

官网:https://learnku.com/docs/laravel/8.x/eloquent/9406

原文地址:https://www.cnblogs.com/bushui/p/14409140.html