How can I write this MySQL using Laravel Query builder? - mysql

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();

Related

Convert SQL query to Query builder Laravel

I want to convert this SQL query to Query builder Laravel
SELECT * FROM articles ORDER BY (titre LIKE '%book%') DESC
Updated:
Try the following code:
DB::table('articles')->orderBy(DB::raw("title LIKE '%$value%'"),'desc')->get();
I think the following one also solves your problem:
DB::table('articles')->orderByRaw("(title LIKE '%book%') DESC")->get();

Convert sql query to eloquent

I'm trying to convert a query to a Laravel query but when I use raw method I can't make it work.
My query:
SELECT * FROM leagues
WHERE SOUNDEX(name)
LIKE CONCAT('%',SUBSTRING(SOUNDEX('Eng. Premier League'),5),'%');
I couldn't find any docs online that answer me.
You can use WhereRaw() to conver this query to Laravel Query Builder.
DB::table('leagues')
->whereRaw("SOUNDEX(name)
LIKE CONCAT('%',SUBSTRING(SOUNDEX('Eng. Premier League'),5),'%')");
if you don't prefer WhereRaw() then you have to use DB::raw() in your Conditions
DB::table('leagues')
->where( DB::raw('SOUNDEX(name)'), 'LIKE', DB::raw("CONCAT('%',SUBSTRING(SOUNDEX('Eng. Premier League'),5),'%')") );
Hope this helps.

Laravel 5.3 Query - Left join some table

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

Writing Query in laravel

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

Eloquent select statement based on a condition in another table

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();