#Laravel - Eloquent ORM数据处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model { protected $table = 'student';
protected $primaryKey = 'id';
protected $fillable = ['name', 'age'];
protected $guarded = [];
public $timestamp = true;
protected function getDateFormat() { return time(); }
protected function asDateTime($val) { return $val; } }
|
1. 使用模型查询数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public function orm1() { $student = Student::all(); dd($student);
Student::find(1001); dd($student);
$student = Student::findOrFail(1001); dd($student);
}
|
2.使用模型新增数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public function orm2() { $student = new Student(); $student->name = 'sean1'; $student->age = 19; $bool = $student->save(); dd($bool);
$student = Student::find(1012); echo $student->created_at; echo date('Y-m-d H:i:s');
$student = Student::create( ['name' => 'imooc', 'age' => 18] ); dd($student);
$student = Student::firstOrCreate( ['name' => 'imoocs', 'age' => 18] ); dd($student);
$student = Student::firstOrNew( ['name' => 'imoocss', 'age' => 18] ); $bool = $student->save(); dd($student);
}
|
3.通过模型更新数据
1 2 3 4 5 6 7 8 9 10 11 12 13
| public function orm3() { $student = Student::find(1014); $student->name = 'kitty'; $bool = $student->save(); var_dump($bool);
$sum = Student::where('id', '>', 1013)->update( ['age' => 32] ); var_dump($sum); }
|
4.通过模型删除数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public function orm4() { $bool = Student::find(1005)->delete(); dd($bool);
$num = Student::detroy(1013); $num = Student::detroy(1013, 1014); $num = Student::detroy([1013,1014]); var_dump($num);
$num = Student::where('id', '>', '1007')->delete(); var_dump($num);
}
|