1

hello friends i have this query that runs using sql editor but i have no idea how to write this query using laravel.please help me out.

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 Answers 3

2

You may try this:

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();
Sign up to request clarification or add additional context in comments.

2 Comments

hello siddharth how to add this part.will you please ellaborate it.FROM (SELECT @b := 0.0) AS dummy CROSS JOIN tbl_bankrecords ORDER BY date
Just try to put all the things mentioned by you in Model::select(DB::raw('PUT YOUR RAW QUERY HERE'))->get();. I'm not sure of it but this should work
2

This should be helpful for you, Anyhow below is the sample code from Laravel documentation.

<?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]);
 }
}

Comments

0

Raw Expressions

Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method:

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

Laravel Doc for Raw Queries

Also :

$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.