当前位置: 主机百科 » 资源 » 技术 » 正文

laravel中怎么使用原生sql?

1.插入数据

1
  DB::insert('insert into users (id,name) values (?,?)',[1, '02405']);

2.查询数据

1
  $user = DB::select('select * from users where id = ?', [1]);  //参数绑定方式  $user = DB::select('select * from users where id = :id', [':id'=>1]);  //命名绑定方式

3.更新数据

1
  $update = DB::update('update users set name="02405.com" where name = ?', ['02405']);

4.删除语句

1
  $delete = DB::delete('delete from users where id = ?',[1]);

 

你也可以使用 Orator(Maurice Calhoun 的在线工具)轻松的将原生和历史遗留 SQL 语句转换为 Laravel 函数式 Query 语句。

你只需输入您的 SQL语句,此工具便会返回一个 Laravel 函数式 Query 语句。

输入:

1
  select id, title, body from posts  where status = 1  order by published_at DESC  limit 10;  

工具将其转换为以下 Laravel 函数式 Query 语句 :

1
  DB::select('id','title','body')      ->from('posts')      ->where('status', '=', 1)      ->orderBy('published_at', 'DESC')      ->limit(10)      ->get();

注意:你必须将反引号(`)替换为 (') 才能正常使用,因为此工具在生成字符串时会使用反引号。

未经允许不得转载:主机百科 » laravel中怎么使用原生sql?

相关文章