laravel的model

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.向模型填充数据

$ php artisan tinker
use AppModelsIssue

Issue::create(['title' => 'PHP Lover'])
Issue::create(['title' => 'Rails and Laravel'])
Issue::all()

4.从模型读取数据

use AppModelsIssue;

$issues = Issue::orderBy('created_at', 'desc')
    ->take(2)
    ->get();
  1. orderBy的意思是排序。
  2. desc是倒序。
  3. take(2)是只读取两条数据。
 

5.添加一个资源

use AppModelsIssue;

Issue::create($request->all());

6.删除一个资源

use AppModelsIssue;

Issue::destroy($id);

7.修改一个资源

use AppModelsIssue;

$issue = Issue::find($id);
$issue->update($request->all());
原文地址:https://www.cnblogs.com/jasonLiu2018/p/11866243.html