Hello i'm new to laravel framework
i have a MySQL query .This work perfectly fine.
select sample.name, ABS((COALESCE(sample.openingbalance, 0)) + COALESCE(trs.TotalAmount, 0)) from sample left join (select ledger,sum(amount) AS TotalAmount from transaction group by transaction.ledger) AS trs on sample.name = trs.ledger
I want to write this query so that it is executed in laravel framework
i tried the following query but its not working
DB::table('sample')->select('sample.name',abs((COALESCE('sample.openingbalance',0))+COALESCE('trs.totalamount',0)))->leftjoin('transaction','sample.name','=','transaction.ledger')->select('ledger','sum(amount) as totalamount')->groupBy('transaction.ledger as trs') ->get();
i think what you need is this.
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:
sample code
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
for more info please refer http://laravel.com/docs/5.1/queries#selects
Related
I am a new Laravel learner and having difficulty to convert from sql
here is my sql
select sum(employee_income)
from employee
group by employee_id, employee_department
this query works when I test.
here is my simplified Laravel but it doesn't work.
DB::raw('(select sum(employee_income) from employee group by employee_id, employee_department)')
Can anybody see something wrong?
You shouldn't use DB::raw() unless you have to. Laravel has the Eloquent Query Builder, which provides an easy to type, Database-agnostic (works with all DBs) method of writing queries. This one should be pretty simple:
$sum = Employee::groupBy('employee_id')
->groupBy('employee_department')
->sum('employee_income');
// Or, if you don't have an `Employee.php` model
$sum = DB::table('employees')
->groupBy('employee_id')
->groupBy('employee_department')
->sum('employee_income');
i am little bit confused that how my query convert in laravel..
select users.username,users.photo, questions.*,
(Select count(*) from answers
where answers.q_id=questions.id) as aAccount from questions
INNER JOIN users ON users.id=questions.user_id
Use Raw 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
DB::table('questions')
->join('users', 'users.id', '=', 'questions.user_id')
->select('users.username','users.photo', 'questions.*',
DB::raw("
( Select count(*) from answers
where answers.q_id=questions.id
)as 'aAccount'")
->get();
I upvoted JYoThl answer as it's exactly how I'd breakdown this query into eloquent, though in instances where a portion of your Eloquent query becomes raw, I personally prefer keeping the entire sql raw. You can still inject variables into it if required.
In my experience, the amount of time spent normalizing a more complex query like this will be used when you go back to the code to re-read it.
Here's how you would pass your sql in it's raw format. I also like to convert the array into a collection, as collections offer a variety of methods. Hope this helps!
$questions = collect(DB::select( DB::raw("
select users.username,users.photo, questions.*,
(Select count(*) from answers where answers.q_id=questions.id) as aAccount
from questions
INNER JOIN users ON users.id=questions.user_id")
));
You would add variables into an array() area if you want to inject a variable. If you wanted to do that you would do something like this:
DB::select( DB::raw("select * from user where user = :user"), array('user' => $user))
I'm trying to get the most recent record for each candidate_id from a ìnterviews` table.
This is what I want to achive:
I'm using Eloquent on laravel and have already tried this methods (with and without eloquent):
$candidates = DB::table('interviews')->select('interviews.*', 'i2.*')
->leftJoin('interviews as i2',
function ($join) {
$join->on('interviews.candidate_id', '=', 'i2.candidate_id');
$join->on('interviews.created_at', '<', 'i2.created_at');
}
)
->whereNull('i2.candidate_id')
->get();
and with eloquent I've tried this:
$candidates = Interview::leftJoin('interviews as i2',
function ($join) {
$join->on('interviews.candidate_id', '=', 'i2.candidate_id');
$join->on('interviews.created_at', '<', 'i2.created_at');
}
)->whereNull('i2.candidate_id')
->get();
If I change get() to toSql() I have exactly the same query that's shown on the above image, but running on laravel I'm getting always these results (this using the first method, with query builder):
Anyone know why I get this results? Is hard to understand that laravel is doing the same query that I do in HeidiSql but I get diferent results :(
Any tip?
Thanks in advance!
Because you are using ->select('interviews.*', 'i2.*') combined with ->whereNull('i2.candidate_id') I am assuming the second select parameter is overriding all fields on the interviews table with nulls, try reversing the order to ->select('i2.*','interviews.*') or not use the i2.* at all.
This is because the output ignores the alias and only uses the fieldname as element key in the returned collection.
Hope it works.
Perfect case scenario you pick the exact columns you want from each of the joined tables for e.g. it may go like this: table1.id,table1.column1,table1.column2,table2.column2 as smth_so_it_doesnt_override
I have an laravel eloquent select statement which looks like this:
$test = Test::with(['a.b.companies']) .. and so on
Now, I want to return results for this query based on some company names in companies table.
I tried to write a where clause with various trial and errors but it doesn't work. I am new to laravel and mysql. Any help in the right direction will be good. thanks.
You may use where, for more reference : - Eloquent ORM
$test = Test::where('company_name1', '=', $company_name1)->orWhere('company_name2', '=', $company_name2)->get();
I have the following MySQL query and I would like to change it to the correct format for Laravel's Query builder.
SELECT DISTINCT(colors) FROM `cards` ORDER BY LENGTH(colors) DESC
This is what I currently have:
table('cards')
->orderBy(LENGTH(colors), 'desc')
->get();
Note that you have to use raw methods to be able to run SQL functions like LENGTH().
This should work:
DB::table('cards')
->select('colors')
->distinct()
->orderByRaw('LENGTH(colors) DESC')
->get();