Convert MariaDB SQL into Laravel Query - sql

This is the working SQL in MariaDB:
SELECT * FROM ticket_categories
WHERE cat_name LIKE '%test%'
AND
( cat_parent_id = 236
OR cat_id = 236
OR cat_parent_id
IN (SELECT cat_id FROM ticket_categories Where cat_parent_id = 236)
)
What I have in Laravel Query so far:
$categoryList->where('ticket_categories.cat_name','like','%'.$request->input('name_filter').'%')
->where(function($query) use($request) {
query->where('ticket_categories.cat_parent_id', '=', $request->input('departments_filter'));
$query->orWhere('ticket_categories.cat_id','=', $request->input('departments_filter'));
$query->orWhereIn('ticket_categories.cat_parent_id', function($query1) use ($request) {
$query1->select('cat_id')
->from(with(new TicketCategory)->getTable())
->where('cat_parent_id', '=', $request->input('departments_filter'));
});
});
My code is now working but you can you can look for people's answer that is much cleaner.

First, I would rewrite your raw MariaDB query as follows:
SELECT *
FROM ticket_categories tc1
LEFT JOIN ticket_categories tc2
ON tc1.cat_parent_id = tc2.cat_id AND
tc2.cat_parent_id = 236
WHERE
tc1.cat_name LIKE '%test%' AND
(
tc1.cat_parent_id = 236 OR
tc1.cat_id = 236 OR
tc2.cat_id IS NOT NULL
);
This would correspond to the following Laravel code:
$results = DB::table('ticket_categories tc1')
->leftJoin('ticket_categories tc2', function($join) {
$join->on('tc1.cat_parent_id', '=', 'tc2.cat_i ');
$join->on('tc2.cat_parent_id', '=', 236);
->where('tc1.cat_name', 'like', '%test%')
->where(function($q) {
$q->where('tc1.cat_parent_id', 236)
->orWhere('tc1.cat_id', 236)
->OrWhereNotNull('tc2.cat_id')
})
->get();
Note that this answer assumes that a given category would have only one parent. If not, then my left join approach could generate duplicates. A workaround would be to use an EXISTS query in the WHERE clause.

Related

Eloquent select with join and not exists in raw statement

I need to write select statement like that:
SELECT co.id FROM client_order co
INNER JOIN client_order_status cos ON cos.id = co.order_status_id AND cos.name IN ('for_shipping', 'to_be_shipped_later')
WHERE NOT EXISTS (SELECT 1 FROM dpackage dp WHERE dp.order_id = co.id AND dp.is_spec_label_generated = 1)
ORDER BY co.id
In Eloquent my expression looks like that:
$clientOrderEntities = ClientOrder::join('client_order_status', 'client_order_status.id', '=', 'order_status_id')
->whereIn('client_order_status.name', ['for_shipping', 'to_be_shipped_later'])
->whereNotExists(function($query) use($orderId) {
$query->select(DB::raw(1))
->from('dpackage')
->where([
['order_id', '=', $orderId]
['is_spec_label_generated', '=', 1]
]);
})->get();
I don't know how to pass orderId from first part of query into whereNotExists sub query
At the moment it looks:
$clientOrderEntities = ClientOrder::join('client_order_status', 'client_order_status.id', '=', 'order_status_id')
->whereIn('client_order_status.name', ['for_shipping', 'to_be_shipped_later'])
->whereNotExists(function($query) {
$query->select(DB::raw(1))
->from('dpackage')
->where([
['order_id', '=', 'client_order.id'],
['is_spec_label_generated', '=', 1]
]);
})
->select('client_order.*')
->get();
This query works:
$clientOrderEntities = ClientOrder::join('client_order_status', 'client_order_status.id', '=', 'order_status_id')
->whereIn('client_order_status.name', ['for_shipping', 'to_be_shipped_later'])
->whereRaw(' NOT EXISTS (SELECT 1 FROM dpackage dp WHERE dp.order_id = client_order.id AND dp.is_spec_label_generated = 1) ')
->select('client_order.*')
->get();
This query works too and is faster than eloquent statements, as #Newbie wrotes, but I don't know why his answer has been deleted:
$clientOrderEntities = DB::select('SELECT co.* FROM client_order co INNER JOIN client_order_status cos ON cos.id = co.order_status_id AND cos.name IN ("for_shipping", "to_be_shipped_later") WHERE NOT EXISTS (SELECT 1 FROM dpackage dp WHERE dp.order_id = co.id AND dp.is_spec_label_generated = 1) ');
Maybe defining name for the tables help you with this.
$clientOrderEntities = \DB::table('client_order as co')
->join('client_order_status as cos', 'cos.id', '=', 'co.order_status_id')
->whereIn('cos.name', ['for_shipping', 'to_be_shipped_later'])
->whereNotExists(function($query) {
$query->select(DB::raw(1))
->from('dpackage')
->where([
['order_id', '=', 'co.id'],
['is_spec_label_generated', '=', 1]
]);
})->get();

Laravel Query: implement Eloquent Scope for Query Builder

In the Laravel Query Builder I want to implement something like Scope in Eloquent.
Ref: Laravel Queries: Adding custom feature like Soft Deletes.
I have some complex queries (with joins and what not) but I want to be able to easily apply a WHERE condition that works as follows:
original:
Select * from t1 join t2 ... join t3 ... etc
Where t1.c1 = x OR t3.c4 like "%like"
wanted:
Select * from t1 join t2 ... join t3 ... etc
Where (t1.c1 = x OR t3.c4 like "%like") AND (t1.isTest = false AND t3.isTest = false)
I have written the following method:
public static function scopeNoTest($query, $tables=[false])
{
if (!is_array($tables)) $tables = [$tables];
foreach ($tables as $table)
{
$field = ($table) ? $table . '.isTest' : 'isTest';
$query = $query->where(function ($q) use ($query, $field)
{
$q->where($field, false)
->orWhereNull($field);
}
);
}
return $query;
}
It gets run like this:
$select = <parameter driven select statement>
$where[$role] = <array of different where condition based on passed in parameter?
$bindings = <query bindings based on passed in parameters>
$query = DB::table('Transactions AS trans')
->leftJoin('Buyers AS b', 'trans.ID', '=', 'b.Transactions_ID')
->leftJoin('Sellers AS s', 'trans.ID', '=', 's.Transactions_ID')
->leftJoin('Agents AS ba', 'trans.BuyersAgent_ID', '=', 'ba.ID')
->leftJoin('Agents AS sa', 'trans.SellersAgent_ID', '=', 'sa.ID')
->leftJoin('TransactionCoordinators AS btc', 'trans.BuyersTransactionCoordinators_ID', '=', 'btc.ID')
->leftJoin('TransactionCoordinators AS stc', 'trans.SellersTransactionCoordinators_ID', '=', 'stc.ID')
->leftJoin('lu_UserRoles AS lu_ur', 'trans.ClientRole', '=', 'lu_ur.Value')
->leftJoin('Properties AS p', 'trans.Properties_ID', '=', 'p.ID')
->selectRaw($select);
// ... Adds code to Only Select records with isTest NOT True
$query = Model_Parent::scopeNoTest($query, ['trans', 'ba', 'sa', ]);
$query->whereRaw($where[$role].$whereUser, $bindings)->distinct();
$transactions = $query->get();
The problem with this code is that it does not put the original [passed in] query in parentheses - so the query is wrong!.
The WHERE the code creates is:
where
(`trans`.`isTest` = 0 or `trans`.`isTest` is null)
and (`ba`.`isTest` = 0 or `ba`.`isTest` is null)
and (`sa`.`isTest` = 0 or `sa`.`isTest` is null)
and trans.BuyersTransactionCoordinators_ID = 1 OR trans.SellersTransactionCoordinators_ID = 1
OR trans.CreatedByUsers_ID = 1 OR trans.OwnedByUsers_ID = 1
And I want
where
(`trans`.`isTest` = 0 or `trans`.`isTest` is null)
and (`ba`.`isTest` = 0 or `ba`.`isTest` is null)
and (`sa`.`isTest` = 0 or `sa`.`isTest` is null)
and (trans.BuyersTransactionCoordinators_ID = 1 OR trans.SellersTransactionCoordinators_ID = 1
OR trans.CreatedByUsers_ID = 1 OR trans.OwnedByUsers_ID = 1)
Is there a way to do this ??
It looks like the following line is causing this:
$query->whereRaw($where[$role].$whereUser, $bindings)->distinct();
I think there are two ways to solve this:
// 1
->whereRaw('(' . $where[$role].$whereUser . ')', $bindings)->
// 2
->where(function ($query) use (...) {
$query->whereRaw(...);
})->

Eloquent 2 left join query

I would like to execute the following query using Laravel's eloquent query builder:
SELECT a.*, b.day, c.sex FROM hours as a
left join reserves as b
on a.id = b.hour_id and b.day = '2015-12-12'
left join doctors as c
on a.doctor_id = c.id
where a.doctor_id = 1;
I have tried the following:
Hour::leftJoin('reserves', function($join) {
$join->on('hours.id' , '=' , 'reserves.hour_id')
->where('reserves.day' , '=' , '2015-12-12');
})
->leftJoin('doctors', function($join) {
$join->on('hours.doctor_id', '=', 'doctors.id');
})
->where('hours.doctor_id', '=', $doctorId)
->get();
Unfortunately, I am not getting the same results.
Everything looks fine, however you miss selecting columns, after Hour:: you should add:
select('hours.*'.'reserves.day','doctors.sex')->
You could also make second join simpler and use aliases, so the final code could look like this:
Hour::select('hours.*'.'reserves.day','doctors.sex')
->from('hours AS a')
->leftJoin('reserves AS b', function($join) {
$join->on('a.id' , '=' , 'b.hour_id')
->where('b.day' , '2015-12-12');
})
->leftJoin('doctors AS c', 'a.doctor_id', '=', 'c.id')
->where('a.doctor_id', $doctorId)
->get();
Of course as $doctorId you should set 1 to get exact same result
you can use DB::raw :
Hour::select(DB::raw('hours.*'),reserves.day, c.doctors)
->leftJoin('reserves',DB::raw("hours.id = reserves.hour_id AND reserves.day='2015-12-12'") ,DB::raw(''), DB::raw(''))
->leftJoin('doctors','hours.doctor_id', '=', 'doctors.id')
->where('hours.doctor_id', '=', $doctorId)
->get()
the 2 empty DB::raw is because leftJoin expect 4 arguments(table,columnA,operator,columnB)

Multi join select query on Laravel

How to write this query in Laravel. I am new in laravel.
Example:
SELECT * FROM ((respassanger join ((`reservation` join flightres
on flightres.res_id = reservation.id)) on respassanger.res_id = reservation.id)
join passanger on respassanger.pas_id = passanger.pas_id)
Have you read the documentation? Checkout Laravel's query builder. Using your table names as mentioned, work from the following example in the docs for your needs:
DB::table('users')
->join('contacts', function($join)
{
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get();
So something like:
DB::table('respassanger')
->join('reservation', function($join)
{
$join->on('flightres.res_id', '=', 'reservation.id')
})
->join('passanger', 'respassanger.pas_id', '=', 'passanger.pas_id')
->select( ... )
->get();
Not sure how correct the above is, but tweak it if it doesn't work.

Select sql code in Laravel

Following query returning six values
SELECT tbl_start FROM timetable inner join route ON tbl_rte_id = id WHERE rte_origin = "UL" and rte_destination = "HW" ORDER BY(tbl_start) DESC;
And my laravel code is returning only one value
$tables = Timetable::join('route', 'tbl_rte_id', '=', 'id')
->where('rte_origin', $origin, 'AND')
->where('rte_destination', $destination)
->orderBy('tbl_start', 'desc')
->get();
foreach ($tables as $table) {
$result[$table->id] = $table->tbl_start;
}
This laravel code is not similar or similar. Can anyone help me.
Change this part:
->where('rte_origin', $origin, 'AND')
// to:
->where('rte_origin', $origin)
It will know by default that it's AND operator
And if you want to provide this operator, then do this:
->where('rte_origin', '=', $origin, 'AND')
You may try something like this:
$tables = Timetable::join('route', 'tbl_rte_id', '=', 'timetable.id')
->where('rte_origin', $origin)
->where('rte_destination', $destination)
->orderBy('tbl_start', 'desc')
->get()->lists('tbl_start', 'id');
The $tables will contain an array of id => tbl_start pairs.
Add a listener in your routes.php
Event::listen('illuminate.query', function($sql){
var_dump($sql);
});
Then execute both queries and check if you have the same result