laravel中执行原生sql语句

在`laravel`中我们有很多种方法来操作`数据库`

今天我们来看看如何用`DB`来执行原生的`sql`

首次在`controller`中用

>use Illuminate\Support\Facades\DB;

```
public function db(){
//添加数据
DB::insert("insert into `table` ( `value`, version) values (?, ? )",[1, 'Laravel']);
DB::insert("insert into `table` set `value`=?,version=?",['value1','1']);

//查询
$user = DB::select('select * from `table` where id = ?', [1]);
echo "

";
print_r(get_object_vars($user[0]));
$user = DB::select('select * from `table` where id = :id', [':id'=>2]);
print_r(get_object_vars($user[0]));

//更新
$result = DB::update('update `table` set value="laraveltest" where id = ?', ['1']);
if($result){
echo "修改成功!";
}else{
echo "修改失败";
}

//删除
$deleted = DB::delete("delete from `table` where id=?",[3]);
if($deleted){
echo "删除成功";
}else{
echo "删除失败";
}
}
```

    A+
发布日期:2020年11月23日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: