如何在laravel中编写sql查询

时间:2016-05-13 05:23:11

标签: sql laravel

你好朋友我有这个使用sql编辑器运行的查询,但我不知道如何使用laravel.please帮助我编写这个查询。

SELECT 
  date,
  memo,
 (COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) total_debits,
 (COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) total_credits,
@b := @b + (COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) - (COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) balance
FROM
(SELECT @b := 0.0) AS dummy 
CROSS JOIN
tbl_bankrecords
ORDER BY
date

3 个答案:

答案 0 :(得分:0)

  

原始表达

     

有时您可能需要在查询中使用原始表达式。这些表达式将作为字符串注入到查询中,因此请注意不要创建任何SQL注入点!要创建原始表达式,可以使用DB :: raw方法:

$users = DB::table('users')
   ->select(DB::raw('count(*) as user_count, status'))
   ->where('status', '<>', 1)
   ->groupBy('status')
   ->get();

Laravel Doc for Raw Queries

另外:

$someVariable = Input::get("some_variable");

$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), array('somevariable' => $someVariable));

http://fideloper.com/laravel-raw-queries

答案 1 :(得分:0)

你可以试试这个:

Model::select(DB::raw('SELECT 
  date
 ,memo
 ,(COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) total_debits
 ,(COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) total_credits,
@b := @b + (COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) - (COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) balance'))->get();

答案 2 :(得分:0)

This应该对您有所帮助,无论如何,以下是Laravel文档中的示例代码。

<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
/**
 * Show a list of all of the application's users.
 *
 * @return Response
 */
 public function index()
 {
    $users = DB::select('select * from users where active = ?', [1]);

    return view('user.index', ['users' => $users]);
 }
}