1.创建模型
$ php artisan make:model Models/Issue
2.模型的白名单机制,用于赋值
class Issue extends Model
{
//指定表名
protected $table = 'article2';
//指定主键
protected $primaryKey = 'article_id';
//是否开启时间戳
protected $timestamps = false;
//设置时间戳格式为Unix
protected $dateFormat = 'U';
//过滤字段,只有包含的字段才能被更新
protected $fillable = ['title','content'];
//隐藏字段
protected $hidden = ['password'];
}
class Issue extends Model
{
protected $fillable = ['title'];
}
3.向模型填充数据
use App\Models\Issue
Issue::create(['title' => 'PHP Lover'])
Issue::create(['title' => 'Rails and Laravel'])
Issue::all()
4.从模型读取数据
use App\Models\Issue;
$issues = Issue::orderBy('created_at', 'desc')
->take(2)
->get();
- orderBy的意思是排序。
- desc是倒序。
- take(2)是只读取两条数据。
5.添加一个资源
use App\Models\Issue;
Issue::create($request->all());
6.删除一个资源
use App\Models\Issue;
Issue::destroy($id);
7.修改一个资源
use App\Models\Issue;
$issue = Issue::find($id);
$issue->update($request->all());