Laravel -- 模型

模型文件

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    //指定表名
    protected $table = 'student';
    //指定主键
    protected $primaryKey = 'id';
    //设置Unix 时间戳
    protected $dateFormat = 'U';
    //指定允许批量赋值的字段,和Model::create()添加数据一起使用
    protected $fillable = ['name'];
    //指定不允许批量赋值的字段
    protected $guarded = [];
}

 

使用模型查询数据

public function  orm1(){
        //查询所有并返回一个集合
        $students = Student::all();

        //根据主键id来查询
        $students = Student::find(1);

        //根据主键查找,查不到就报错
        $students = Student::findOrFail(3);

        //根据条件进行查询
        $students = Student::where('name','=','xian')->first();
        dd($students);

        //指定返回几条数据
        Student::chunk(3, function ($students){
            dd($students);
        });

使用模型新增数据

public  function orm2(){
        //使用模型新增数据
        $student = new Student();
        $student->name = 'jianqiao';
        $bool=$student->save();
        dd($bool);

    }

使用create方法添加数据

//使用模型create方法添加数据
        $student = Student::create([
            'name'=>'joker','age'=>18
        ]);
        dd($student);
//firstOrCreate()若查找不到则添加数据并返回新的实例
        $student = Student::firstOrCreate(
            ['name'=>'imooc','age'=>38]
        );
        dd($student);

使用模型修改数据

public function orm3(){
        $students = Student::find(5);
        $students->age=27;
        $bool=$students->save();
        dd($bool);
    }

使用模型删除数据

public function orm4(){
        //通过模型删除数据
        $students = Student::find(12);
        $bool=$students->delete();
        dd($bool);
        //通过主键删除
        $num = Student::destroy(13);
        dd($num);
        $num = Student::destroy([1,2]);
        dd($num);
        //通过条件删除
        $num = Student::where('name','=','root')->delete();
        dd($num);
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

//指定表名
protected $table = 'student';
//指定主键
protected $primaryKey = 'id';
//设置Unix 时间戳
protected $dateFormat = 'U';
//指定允许批量赋值的字段,Model::create()添加数据一起使用
protected $fillable = ['name'];
//指定不允许批量赋值的字段
protected $guarded = [];
posted @ 2018-07-17 12:38  白po  阅读(141)  评论(0编辑  收藏  举报