Laravel 5.1 CURD 入门
数据库的model类的增删查改
1.1新建模型类
例如:数据库有个叫做xm_gg的表主键是id,我们设置表前缀为xm_,则模型名为GgModel
,模型的路径应在/app/Http/Model
,因为我封装了模块Modules:shop,所以模型路径为/app/Modules/Shop/Models/GgModel.php
;
<?php
/**
* gg模型
*/
namespace App\Modules\Shop\Models;
class GgModel extends Model
{
//真实表名
protected $table = 'gg';
//数据表的主键 默认id
protected $primaryKey = 'id';
//模型日期列的存储格式 U 使用时间戳作为时间类型
protected $dateFormat = 'U';
// 是否自动添加时间戳
// public $timestamps = false;
//可以被批量赋值的属性
protected $fillable = ['name'];
//不想被赋值的属性数组
//protected $guarded = ['price'];
}
1.2查询
// 查询第一条数据 返回数据对象
$data = GgModel::first();
// 获取总数据量 返回数字
$data = GgModel::count();
// 获取id为8的数据 返回数据对象
$data = GgModel::find(8);
// 获取id为8的数据 返回数组
$data = GgModel::find(8)->toArray();
//获取全部数据 返回数组
$data = GgModel::get()->toArray();
//获取全部数据 返回数组
$data = GgModel::all()->toArray();
//获取表内某个字段的值 返回数组
$data = GgModel::lists('name')->toArray();
//获取表内多个字段的值 返回二维数组 二维数组的键名为:id,键值为name
//注:不可使用有重复值的作为键名
$data = GgModel::lists('name','id')->toArray();
$data = GgModel::lists('name','created_at')->toArray();
$data = GgModel::lists('id','created_at')->toArray()