使用make:model
命令
php artisan make:model Post
创建模型的同时并创建对应的数据库迁移文件
php artisan make:model Post -m
protected $table = ‘articles‘;
protected $primaryKey = ‘post_id‘;
设置主键不自增
public $incrementing = false;
设置主键类型
protected $keyType = ‘string‘;
设置不自动维护时间戳
public $timestamps = false;
通过CREATED_AT
和UPDATED_AT
常量设置自定义的创建和更新时间字段:
public const CREATED_AT = ‘create_time‘;
public const UPDATED_AT = ‘update_time‘;
修改时间存储格式
protected $dateFormat = ‘U‘;
protected $connection = ‘connection_name‘;
使用方法all
$posts = Post::all();
指定查询条件和查询字段,通过where
和select
方法实现
$posts = Post::where(‘views‘,‘>‘,0)->select(‘id‘,‘title‘,‘content‘)->get();
$user = User::where(‘name‘,‘bigcola‘)->first();
查询条件为主键,通过find
方法实现
$user = User::find(1);
模型查询结果为空时返回null
,可通过使用firstOrFail
或者findOrFail
方法在找不到对应记录时抛出404异常
$num = User::whereNotNull(‘email_verified_at‘)->count(); # 计数
$sum = User::whereNotNull(‘email_verified_at‘)->sum(‘id‘); # 求和
$avg = User::whereNotNull(‘email_verified_at‘)->avg(‘id‘); # 平均值
$min = User::whereNotNull(‘email_verified_at‘)->min(‘id‘); # 最小值
$max = User::whereNotNull(‘email_verified_at‘)->max(‘id‘); # 最大值
先实例化模式实例,依次赋值,最后调用save
方法
$post = new POST;
$post->title = ‘测试标题‘;
$post->content = ‘测试内容‘;
$post->save();
$post = Post::find(1);
$post->title = ‘更新标题‘;
$post->save();
先查询,再删除
$post = Post::find(1);
$post->delete();
通过主键删除
Post::destroy([1,2,3]);
原文:https://www.cnblogs.com/bigcola/p/13378864.html