laravel增删改查

1.使用命令自动创建model层 进入所在目录php artisan make:model Test

2增删改查(toArray()将数据变成数组)

1. 查

public  functionuserTest(){//测试用方法


    return$this->all();//拿全部数据(或get)
   // return $this->find("");//拿一条数据
   // return $this->where("username","ceshi")->get();//根据条件拿一条数据
   // return $this->where("id","<","2")->get();//根据条件拿一条数据
}


 

2. 增(默认有两个字段,可以在model层关闭,或者在表中添加)

public$timestamps=false;//关闭自动寻找的创建时间和更新时间的字段


public functionuserAdd(){
  //  $this->username="ceshi1";//保存一个数据
    //保存一个数组
    $data=[
        "a"=>"qqq",
        "b"=>"www"
    ];
    $this->fill($data);
    $this->save();
}


2. 修改

    public functionupdate(){
        //修改一条数据
//    $user =$this->find(2);//查数据
//    $user->username="修改";
//        $user->save();//单个数据需要保存
        //批量修改数据
        $users=$this->where("id","<",6);
        $users->update(['username'=>'ceshi','age'=>10]);//自带save不用写
    }

5. 删除
 

public functiondel(){
        $user=$this->find(3);//先查出来
        $user->delete();
    }


6.dd()方法相当于var_dump()和die;
 

猜你喜欢

转载自blog.csdn.net/qq_15036711/article/details/88107787