标签:控制 primary mina model delete name namespace pac 维护
//模型中的相关代码
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model{
//默认对应的是模型复数,即students,如果不是,需要自己指定表名
protected $table = ‘student‘;//指定表名
//默认主键是id,如果不是,需要指定
protected $primaryKey = ‘id‘;
//自动维护时间戳
public $timestamps = true;
protected function getDateFormat()
{
return time();
}
//不格式化时间戳
protected function asDateTime($val)
{
return $val;
}
//指定允许批量赋值的字段
protected $fillable = [‘name‘,‘age‘];
//指定不允许批量赋值的字段
protected $guarded = [‘name‘,‘age‘];
}
//控制器的相关代码
//orm 使用模型查询
public function orm1(){
//all().返回模型的对象
$student = Student::all();
//find()
$student = Student::find(100);
//findOrFail(),查找不到就报错
$student = Student::findOrFail(100);
//get()
$student = Student::get();
//first()
$student = Student::where(‘id‘,‘>‘,10)
->orderBy(‘age‘,‘desc‘)
->first();
}
//orm 使用模型查询
public function orm2(){
//使用模型新增数据
$student = new Student();
$student->name = ‘hello‘;
$student->age = ‘hello‘;
$bool = $student->save();
var_dump($bool);
//格式化日期
$student = Student::find(1);
echo date(‘Y-m-d H:i:s‘,$student->addtime);
//使用模型的create方法新增数据,
$student = Student::create([‘name‘=>‘haha‘,‘age‘=>10]);
//firstOrCreate,先查找,若没有则新增
$student = Student::firstOrCreate([‘name‘=>‘haha‘]);
//firstOrNew,先查找,若没有则返回实例,需要自行调用save新增
$student = Student::firstOrNew([‘name‘=>‘haha‘]);
$bool = $student->save();
//通过模型更新数据
$student = Student::find(10);
$student->name = ‘happy‘;
$bool = $student->save();
var_dump($bool);
//批量更新,返回行数
$num = Student::where(‘id‘,‘>‘,10)->update(
[‘age‘=>20]
);
var_dump($num);
//通过模型删除,不存在会报错
$student = Student::find(10);
$bool = $student->delete();
var_dump($bool);
//通过主键删除
$num=Student::destroy(10);
var_dump($num);
$num=Student::destroy([10,11,20]);
var_dump($num);
$num=Student::where(‘id‘,‘>‘,20)->delete();
var_dump($num);
}
标签:控制 primary mina model delete name namespace pac 维护
原文地址:https://www.cnblogs.com/gyfluck/p/9040061.html