热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

laravel数据库操作(curd,软删除,数据迁移与执行,使用faker填充数据)

使用Facades

使用Facades

namespace App\Http\Controllers;use Illuminate\Support\Facades\DB;
class StudentController extends Controller
{//public function test1(){//query$student = DB::select('select name,age from student');//insert$bool = DB::insert("insert into student(name, age) values(?, ?)",["imooc", 18]);//update$num = DB::update('update student set age = ? where name = ?', [20, 'sean']);//delete$num = DB::delete("delete from student where name = ?" , ["sean"]);//占位符$res = DB::selectOne("select * from class where id = :id", [':id' => 5]);dump($student);}
}

使用构造查询器


sql语句如下:CREATE TABLE student (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) DEFAULT NULL,
age TINYINT(3) DEFAULT NULL,
sex TINYINT(3) DEFAULT NULL,
create_at INT(11) DEFAULT NULL,
update_at INT(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=MYISAM DEFAULT CHARSET=utf8;


public function query1() {//insert$res = DB::table("student")->insert(['name'=>'imooc', 'age'=>18]);//insertGetId$id = DB::table("student")->insertGetId(['name'=>'imooc1', 'age'=>18]);//insert multi rowsDB::table("student")->insert([['name'=>'imooc1', 'age'=>18],['name'=>'imooc2', 'age'=>18]]);var_dump($id);//int(4)}public function query2() {//update$num = DB::table("student")->where("id", 4)->update(['age'=>30]);//increment and decrement$num = DB::table('student')->increment('age', 3);$num = DB::table('student')->where("id", 4)->decrement('age', 3, ['name'=>'test']);}public function query3() {//deleteDB::table("student")->where("id", ">=", 3)->delete();DB::table("student")->truncate();}public function query4() {//get all$students = DB::table("student")->get();//get the first item of query result$student = DB::table("student")->orderBy("id", "desc")->first();//orWhere$student = DB::table("student")->where("id",4)->orWhere("name",'tom')->first();//闭包查询$kw = $request->get("kw");//如果$kw为真则执行匿名函数里的查询$res = DB::table('class')->when($kw, function(Builder $query) use ($kw) {$query->where('pid','like',"%{$kw}%");})->get();//多条件查询$students = DB::table("student")->whereRaw("id >= ? and age > ?", [5, 20])->get();//pluck (返回指定的字段)$names = DB::table("student")->pluck("name");//lists (效果同pluck) 但可以指定第二个参数值为下标$list = DB::table("student")->lists("name", "id");//select 同tp5中的column$names = DB::table("student")->select("id", "name", 'age')->get();//chunk 用法同tp5DB::table("student")->chunk(2, function($students) {var_dump($students);});}public function query5() {$num = DB::table("student")->count();DB::table("student")->max("age");DB::table("student")->min("age");DB::table("student")->sum("age");var_dump($num);}

Eloquent ORM


默认情况下,模型文件在laravel的根目录下。
创建模型的命令 php artisan make:model Model/Article



在这里插入图片描述


public function orm1() {//get all the items$all = Student::all();//get one by pk [TP5 get]$one = Student::find(1000);// findOrFail() will throw an error if the res does not exist$one = Student::findOrFail(3000);// query by conditionStudent::where("id", ">", 3)->orderBy("id", "desc")->first();Student::chunk(2, function($students){//pass});Student::max("id");}public function orm2() {//if save failed add public $timestamps = false in the model
// $student = new Student();
// $student->name = "sean";
// $student->age = 20;
// $bool = $student->save();//插入的字段需要在模型$fillable中设定$student = Student::create(['name'=>'imooc', 'age'=> 18]);$data = ['name'=>'tom', 'age'=>18];//insert插入,不会自动设置timestampStudent::insert($data);//以属性查找,如没有则新增Student::firstOrCreate(["name" => "imoocfirst"]);//以属性查找,如果没有则新增实例$s = Student::firstOrNew(["name" => "imoocnew"]);$s->save();}public function orm3() {//update by model$student = Student::find(4);$student->name = "update orm3";$bool = $student->save();$num = Student::where("id", ">", 4)->update(['age' => 41]);var_dump($num);}public function orm4() {//delete//1.
// $student = Student::find(4);
// $num = $student->delete();//2. by pk$num = Student::destroy(15,16);//3. by conditionStudent::where("id", ">", 104)->delete();}

软删除配置
1.在migration文件中配置 $table->softDeletes();
2.在模型文件中,引入trait SoftDeletes;
3.在模型文件中配置 protected $dates = [“deleted_at”]

//引入软删除use SoftDeletes;//指定删除的字段标识protected $dates = ['deleted_at'];

查询软删除的数据使用 onlyTrashed()方法,恢复使用 restore()


$res = Article::onlyTrashed()->get();

添加表前缀
在这里插入图片描述



数据库迁移与数据填充


生成迁移


php artisan make:migration create_test_table --create=test
create_test_table 生成的文件后缀名称
–create=test 生成表的名称



编写迁移

$table->字段函数(“字段名”)->约束函数()


Schema::create('users', function (Blueprint $table) {$table->increments('id');$table->string('name');$table->string('email')->unique();$table->string('password');$table->rememberToken();$table->timestamps();});

执行迁移

php artisan migrate
php artisan migrate:rollback --step=4 回滚迁移
php artisan migrate:reset 回滚所有迁移
php artisan migrate:refresh 回滚后再创建
php artisan migrate:fresh 删除数据库中所有的表,再migrate



使用faker

先创建一个seed文件
php artisan make:seeder seedName
在DatabaseSeeder中调用创建的seedClass
在这里插入图片描述


public function run(){//$data &#61; [];$faker &#61; \Faker\Factory::create();for ($i&#61;0; $i<&#61;10; $i&#43;&#43;) {$data[] &#61; [&#39;uid&#39; &#61;> $i,&#39;title&#39; &#61;> $faker->word,&#39;cnt&#39; &#61;> $faker->text];}DB::table("articles")->insert($data);}

调用 php artisan db:seed



使用factory创建

创建工厂文件
php artisan make:factory FactoryName -m Model (如不在app目录下&#xff0c;要带目录&#xff0c;如Models/Article)
生成的文件在database/factories下


use Faker\Generator as Faker;
//定义要创建的数据
$factory->define(App\Models\Article::class, function (Faker $faker) {return [//&#39;uid&#39; &#61;> rand(1, 10),&#39;title&#39; &#61;> $faker->word,&#39;cnt&#39; &#61;> $faker->text];
});

在seed文件中&#xff0c;调用factory()方法


public function run(){//factory(Article::class, 20)->create();}

最后执行 php artisan migrate:refresh --seed 生成数据



推荐阅读
author-avatar
zhouwenjun
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有