3.关于laravel框架中数据库操作-Eloquent ORM

基本简介:Eloquent ORM为laravel自带的ActiveRecord实现,用于数据库操作,每个数据表都有一个与之相对应的“模型”(Model)用于和数据表的交互

1.model的建立,基础model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Test extends Model{

      //指定表名,不指定表名的情况表名就为模型的复数

      protected $tabel = 'test';

      //指定主键

      protected $primaryKey = 'id';

     //自动维护时间戳

     public $timestamps = true;

     //指定允许批量赋值的字段

     protected $fillable = ['name','age'];

     //指定不允许批量赋值的字段

     protected $guarded = ['name','age'];

     //将时间设成time()形式输出

     protected function getDateFormat(){

          return time();

     } 

     //asDateTime($val)===>将时间变成数字格式

     protected function asDateTime($val){

          return $val;

     }

}


Controller创建方法使用ORM查询

public function orm1{

   // all(),输出为集合,查询表的所有记录

   $test = Test::all();=>>>Model名//查询函数

   //find(),根据主键进行查询

   $test1 = Test::find();

   //findOrFail().根据主键查找,没查找到抛出异常

   $test2 = Test::findOrFail

   //和DB facade通用的方法

   Test::get();//查询所有数据

   Test::where('id','>',1)->orderBy('age','desc')->first();

   Test::chunk(2,function($test){

          var_dump($test);

    });

    //聚合函数,max,min,count,avg...

    Test::conut();

}

public function orm2(){

           //使用模型新增数据

           $test =  new Test();

           $test->name = 'name';

           $test->age    = 20;

           $test->save();


           //使用模型的Create方法新增数据

           Test::creat(

                  ['name'=>'test','age'=>20]

            );在没有设置批量赋值的情况下会报错

             //firstOrCreat(),以属性查找信息,如果没有则新增

            Test::firstOrCreat(

                     ['name'=>'test']

             );

             //firstOrNew(),以属性查找信息,若没有,则建立新的实例,但没进行保存操作。若需要保存可以save();

              $test = Test::firstOrNew(

                     ['name'=>'first']

               );

               $bool = $test->save();   

}

未完。。。

public function orm3(){

       //通过模型修改

      $test = Test::find(1);

      $test -> name = 'test';

      $bool = $test->save();

      //批量更新

      $num = Test::where('id','>',2)->update(

               ['name'=>'test2','age'=>20]

        );

}

public function orm4(){

      $test = Test::find(1);

      $test->delete();

      //通过主键删除

      $num = Test::destory(1);

      $num = Test::destory(1,2);

      $num = Test::destory([1,2]);


      $num = Test::where('id','>',2)->delete();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值