Blogger Information
Blog 42
fans 5
comment 0
visits 38503
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
laravel 控制器中控制数据库的增删查改等
张浩刚
Original
1283 people have browsed it

laravel 控制器中控制数据库的增删查改

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\DB; //引入DB,否在无法对数据库操作
  4. $res = DB::table('article')->get(); //从数据表article中获取全部数据

select:查询

  1. $res = DB::table('数据表')->select('字段')->get();
  2. //例仅从article数据表中获取字段为id title的所有数据,,toArray()可以将获取的数据对象转换成数组
  3. $res = DB::table('article')->select('id','title)->get()->toArray();

insert:接收数组形式的字段名和字段值进行插入操作:

  1. $ers = DB::table('数据表')->insert([数组方式=>插入的内容]);
  2. //可以一维数组方式插入
  3. $ers = DB::table('article')->insert(['title'=>'误杀', 'list_id' => 2]);
  4. //也可如下二维方式插入
  5. $arti = DB::table('article')->insert(
  6. [
  7. ['list_id' => 2,'title' => '误杀'],
  8. ['list_id' => 3,'title' => '变身特工']
  9. ]
  10. );
  11. //insertGetId: 如果数据表有自增 ID ,使用 insertGetId 方法来插入记录并返回 ID 值
  12. $ers = DB::table('article')->insertGetId(['title'=>'误杀', 'list_id' => 2]);

update: 更新数据表中内容

  1. $res = DB::table('数据表')->where(更新条件)->update([数组方式=>更新内容]);
  2. //例如, 注意where('id', '=', 3) = 可省略简写;;其他书写方式如 where('id', '>', 3)
  3. $res = DB::table('article')->where('id',3)->update(['title'=>'特工']);

delect: 删除

  1. $arti = DB::table('数据表')->where(删除条件)->delete();
  2. //例如,删除id>10的所有数据
  3. $arti = DB::table('article')->where('id', '>', 10)->delete();

where: 方法

  1. //获取id>10的所有数据
  2. $arti = DB::table('article')->where('id', '>', 10)->get();
  3. //获取id=10的数据
  4. $arti = DB::table('article')->where('id', 10)->get();
  5. //获取id<=4的数据
  6. $arti = DB::table('article')->where('id', '<=', 4)->get();
  7. //获取id在1 5之间所有的数据(包含1,5)
  8. $arti = DB::table('article')->whereBetween('id', [1, 5])->get();
  9. //获取id=1 和id=5的这两条数据(仅id=1,id=5的数据)
  10. $arti = DB::table('article')->whereIn('id', [1, 5])->get();
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:很简洁, 不错
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!