Laravel入门教程(五)- 数据库操作

来源:互联网 发布:php登陆后跳转页面 编辑:程序博客网 时间:2024/05/16 15:28

1. Eloquent ORM简介及查询数据

1.1. Eloquent ORM简介

ActiveRecord实现

ActiveRecord:

1.2. 创建模型并关联数据库表

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Student extends Model{    // 指定表名,默认是Student的复数    protected $table = 'student';    // 指定id    protected $primaryKey = 'id';}

1.3. 查询数据

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm1()    {        // 查看Student表所有的信息        $student = Student::all();        dd($student);        // 查看Student表中id=1001对应的数据,找不到返回NULL        $student = Student::find(2001);        dd($student);        // 查看Student表中id=2001对应的数据,找不到出错        $student = Student::findOrFail(1001);        dd($student);        // 查看表的所有记录        $student = Student::get();        dd($student);        // 排序,条件,取第一个        $student = Student::where('id', '>', '1001')            ->orderBy('age', 'DESC')            ->first();        dd($student);        // 使用chunk        Student::chunk(2, function($students){            var_dump($students);        });        // 聚合函数        $qty = Student::count();        dd($qty);    }}

2. ORM中新增数据

  • 通过模型新增数据(涉及到自定义时间戳)
  • 使用模型的Create方法新增数据(涉及到批量赋值)

2.1. 通过模型来新建记录

在Controller中,设置:

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm2()    {        // 通过模型来新建记录        $student = new Student();        $student->name = 'Belle';        $student->age = 18;        $bool = $student->save();        dd($bool);        $student = Student::find(1009);        echo $student->created_at;        // 显示: 1489460962(需要设置:asDateTime)    }}

在Model中设置:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Student extends Model{    // ... 省略了部分代码    // 自动维护时间戳(timestamp)    public $timestamps = TRUE; // FALSE 不维护时间戳| TRUE 维护    protected function getDateFormat(){        return time();    }    // 如果需要显示的是时间戳    protected function asDateTime($val)    {        return $val;    }}

2.2. 使用模型的Create方法

Controller中设置:

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm2()    {        // 使用模型的Create方法来新增数据        // 如果不设置模型的$fillable,会抛出MassAssignmentException异常        $student = Student::create([            'name' => 'Candy',             'age' => 18]);        dd($student);    }}

Model中设置:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Student extends Model{    // ... 省略了部分代码    // 指定允许批量赋值的字段    protected $fillable = ['name', 'age'];    // 指定不允许批量赋值的字段    protected $guarded = [];}

2.3. firstOrCreate方法

特别适合的情况就是新增的同时保证不会出现重复

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm2()    {        // firstOrCreate()         $student = Student::firstOrCreate(            ['name' => 'Elsa']            );        dd($student);    }}

2.4. firstOrNew方法

firstOrNew()与firstOrCreate()的区别是:firstOrNew不会自动保存到数据库。需要手动调用save()方法来保存。

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm2()    {        // firstOrNew()        // firstOrNew()与firstOrCreate()的区别是:firstOrNew不会自动保存到数据库        // 需要手动调用save()方法来保存        $student = Student::firstOrNew(            ['name' => 'Linda']            );        $bool = $student->save();        dd($bool);    }}

3. 更新数据

3.1. 利用模型更新数据

在Controller中更改,最后用save()保存

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm3()    {        // 通过模型更新数据        $student = Student::find(1010);        $student->name = 'Cindy';        $bool = $student->save(); // updated_at也会改变    }}

TODO: 如何设置要更新的时间戳字段?

3.2. 利用update()函数

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm3()    {        // 使用update()函数批量更新        $qty = Student::where('id', '>', 1011)->update(['age'=>21]);        var_dump($qty);    }}

4. 删除数据

4.1. 通过模型删除数据

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm3()    {        // 通过模型删除        $student = Student::find(1009);        $bool = $student->delete();         var_dump($bool);    }}

4.2. 通过主键删除

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm3()    {        // 通过主键删除        $qty = Student::destroy([1010, 1012]);        var_dump($qty);    }}

4.3. 指定条件删除

<?phpnamespace App\Http\Controllers;use Illuminate\Support\Facades\DB;use App\Student;class StudentController extends Controller{    public function orm3()    {        // 指定条件删除        $qty = Student::where('id', '>' , '1010')->delete();        var_dump($qty);    }}