Converting SQL query to Laravel? - mysql

I have a very large query and many more that are even bigger.
I've tried to convert it to work with Laravel's DB class except it's not returning anything.
Is there something that can do this automatically? Like a converter?
What am I doing wrong here?
SELECT
cases.id
FROM cases
LEFT JOIN cases_cstm ON cases.id = cases_cstm.id_c
JOIN cases_contacts_1_c ON cases.id = cases_contacts_1_c.cases_contacts_1cases_ida AND cases_contacts_1_c.deleted = 0
JOIN contacts ON cases_contacts_1_c.cases_contacts_1contacts_idb = contacts.id AND contacts.deleted = 0
LEFT JOIN contacts_pal_policy_adviser_list_1_c ON contacts.id = contacts_pal_policy_adviser_list_1_c.contacts_pal_policy_adviser_list_1contacts_ida
LEFT JOIN pal_policy_adviser_list ON contacts_pal_policy_adviser_list_1_c.contacts_pal_policy_adviser_list_1pal_policy_adviser_list_idb = pal_policy_adviser_list.id
LEFT JOIN huge__insurance_carriers_cases_1_c ON cases.id = huge__insurance_carriers_cases_1_c.huge__insurance_carriers_cases_1cases_idb AND huge__insurance_carriers_cases_1_c.deleted = 0
LEFT JOIN huge__insurance_carriers ON huge__insurance_carriers_cases_1_c.huge__insurance_carriers_cases_1huge__insurance_carriers_ida = huge__insurance_carriers.id AND huge__insurance_carriers.deleted = 0
LEFT JOIN products_cases_1_c ON cases.id = products_cases_1_c.products_cases_1cases_idb
LEFT JOIN products ON products_cases_1_c.products_cases_1products_ida = products.id
WHERE cases.deleted = 0
AND contacts.id = 'b8a00721-40f1-7801-b4b9-50ce152ce2ec'
AND ((cases.status = 'Entered') or (cases.status = 'Submitted') or (cases.status = 'Approved') or (cases.status = 'Issued') or (cases.status = 'Gathering_Medical_Information') or (cases.status = 'Awaiting_Carrier_Offers') or (cases.status = 'All_Offers_In') or (cases.status = 'Informal_Entered') or (cases.status = 'Await_Del_Req')) GROUP BY cases.id ORDER BY cases_cstm.insured_name_c ASC LIMIT 0, 20
Laravel query
DB::table('cases')
->leftJoin('cases_cstm', 'cases.id', '=', 'cases_cstm.id_c')
->join('cases_contacts_1_c', 'cases.id', '=', 'cases_contacts_1_c.cases_contacts_1cases_ida')
->join('contacts', 'cases_contacts_1_c.cases_contacts_1contacts_idb', '=', 'contacts.id')
->leftJoin('contacts_pal_policy_adviser_list_1_c', 'contacts.id', '=', 'contacts_pal_policy_adviser_list_1_c.contacts_pal_policy_adviser_list_1contacts_ida')
->leftJoin('pal_policy_adviser_list', 'contacts_pal_policy_adviser_list_1_c.contacts_pal_policy_adviser_list_1pal_policy_adviser_list_idb', '=', 'pal_policy_adviser_list.id')
->leftJoin('huge__insurance_carriers_cases_1_c', 'cases.id', '=', 'huge__insurance_carriers_cases_1_c.huge__insurance_carriers_cases_1cases_idb')
->leftJoin('huge__insurance_carriers', 'huge__insurance_carriers_cases_1_c.huge__insurance_carriers_cases_1huge__insurance_carriers_ida', '=', 'huge__insurance_carriers.id')
->leftJoin('products_cases_1_c', 'cases.id', '=', 'products_cases_1_c.products_cases_1cases_idb')
->leftJoin('products', 'products_cases_1_c.products_cases_1products_ida', '=', 'products.id')
->where('contacts.id', '=', 'b8a00721-40f1-7801-b4b9-50ce152ce2ec')
->orWhere('cases.status', '=', 'Entered')
->orWhere('cases.status', '=', 'Submitted')
->orWhere('cases.status', '=', 'Approved')
->orWhere('cases.status', '=', 'Issued')
->orWhere('cases.status', '=', 'Gathering_Medical_Information')
->orWhere('cases.status', '=', 'Awaiting_Carrier_Offers')
->orWhere('cases.status', '=', 'All_Offers_In')
->orWhere('cases.status', '=', 'Informal_Entered')
->orWhere('cases.status', '=', 'Await_Del_Req');
->get();

$statuses = [...]; // array of statuses to compare
DB::table('cases')
// all your joins
->where('contacts.id', '=', 'b8a00721-40f1-7801-b4b9-50ce152ce2ec')
->whereIn(cases.status', $statuses)
->get(['cases.id']);
or (really, don't, just as an example):
DB::table('cases')
// all your joins
->where('contacts.id', '=', 'b8a00721-40f1-7801-b4b9-50ce152ce2ec')
->where(function($q) { // this will wrap all those OR WHERE clauses in AND ( .. )
$q->where(...)
// all the orWheres
->orWhere(...);
})
->get(['cases.id']);
Also, use DB::getQueryLog() after that to get the array of the queries, that were run by Laravel.

Related

Laravel Eloquent left join query

I have like this query which work in plain sql:
SELECT users.id, users.name, roles.name
FROM users
LEFT JOIN model_has_roles ON model_has_roles.model_id = users.id
LEFT JOIN roles ON roles.id = model_has_roles.role_id
ORDER BY roles.name ASC
Using laravel I tried like this but it's doesn't work:
$user = $request->user();
$role = (array) $request->get('role', []);
$order = (array) $request->get('order');
$perPage = $request->get('perPage') ?? 10;
$users = User::where('id', '!=', $user->id);
if(count($role)) {
if (($key = array_search('admin', $role)) !== false) {
unset($role[$key]);
}
$users = $users->whereHas('roles', function ($query) use($role) {
return $query->whereIn('name', $role);
});
} else {
$users = $users->whereHas('roles', function ($query) {
return $query->whereIn('name', ['farmer', 'specialist', 'company']);
});
}
if(count($order) && isset($order['field'])) {
$orderType = $order['type'] ?? 'ASC';
if($order['field'] == 'role') {
$users = $users->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'users.id')
->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
->orderBy('roles.name', $orderType);
} else {
$users = $users->orderBy($order['field'], $orderType);
}
}
$users = $users->paginate($perPage);
Error message:
`"message": "SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select count(*) as aggregate from `users` left join `model_has_roles` on` `model_has_roles`.`model_id` = `users`.`id` left join `roles` on `roles`.`id` = `model_has_roles`.`role_id` where `id` != 3 and exists (select * from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `users`.`id` = `model_has_roles`.`model_id` and `model_has_roles`.`model_type` = App\\Models\\User and `name` in (specialist, company)))",
Because your both models have id and after sql execute the query id column will be ambiguous so this will help you:
$users = User::where('id', '!=', $user->id);
change to
$users = User::where('users.id', '!=', $user->id);
Then try:
$users = $users->select(['users.id', 'users.name', 'roles.name'])
->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'users.id')
->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
->orderBy('roles.name', 'ASC');

How can I make this query in Laravel:

SELECT *
FROM time_table_rup t
INNER JOIN gruppa g ON t.group_id = g.gruppa_id
INNER JOIN discipline d ON t.discipline_id=d.discipline_id
WHERE sikl = 5 AND t.semestr % 2 = 1
Use query builder like this:
DB::table('time_table_rup AS t')
->join('gruppa AS g', 't.group_id', '=', 'g.gruppa_id')
->join('discipline AS d', 't.discipline_id', '=', 'd.discipline_id')
->where('sikl', 5)
->where(DB::raw('t.semestr % 2'),1)
->get()

Converting MySQL query to Laravel

How I can convert this MySQL query to a Laravel query?
select *
from marques
where id in (select marque_id from products
where category_id = 'valeur1' or category_id in (select id from categories
where parent_id = 'Valeur1'))
I think your current query is equivalent to the following:
SELECT *
FROM marques m
LEFT JOIN products p
ON m.id = p.marque_id
LEFT JOIN categories c
ON p.category_id = c.id AND c.parent_id = 'Valeur1'
WHERE
p.category_id = 'valeur1' OR
c.id IS NOT NULL
Here is a rough guess at what your Laravel code might look like:
$res = DB::table('marques')
->join('products', 'marques.id', '=', 'products.marque_id')
->join("categories", function($join) {
$join->on('products.category_id', '=', 'categories.id')
->on('categories.parent_id', '=', 'Valeur1')
})
->whereNotNull('categories.id')
->orWhere('products.category_id', '=', 'valeur1')
->select('*')
->get();

Inner join in laravel

How convert this query in laravel?
SELECT m.thumbnail,e.judul_artikel,e.id_artikel, m.id_artikel
FROM t_artikel e
INNER JOIN t_artikel m on e.parent_id = m.id_artikel
where e.publish='Y'
ORDER BY e.dibaca DESC
LIMIT 3
Try this:
$data= DB::table('t_artikel as e')
->join('t_artikel as m', 'e.parent_id', '=', 'm.id_artikel')
->select('m.thumbnail','e.judul_artikel','e.id_artikel',
'm.id_artikel')
->where('e.publish', '=', 'Y');
->orderBy('e.dibaca', 'DESC')
->limit(3)
->get();
DB::table(DB::raw('t_artikel AS e'))
->join(DB::raw('t_artikel AS m'), DB::raw('e.parent_id'), '=', DB::raw('m.id_artikel'))
->select([
DB::raw('m.thumbnail'),
DB::raw('e.judul_artikel'),
DB::raw('e.id_artikel AS e_id_artikel'),
DB::raw('m.id_artikel AS m_id_artikel')
])
->where(DB::raw('e.publish'), 'Y')
->orderBy(DB::raw('e.dibaca'), 'DESC')
->take(3)
->get();

Mysql - SQLSTATE[42S22]: Column not found: 1054 Unknown column

This is my the code of my query :
$payments = DB::table('payments')
->join('invoices', 'invoices.id', '=', 'payments_invoices.invoice_id')
->join('payments_invoices', 'payments.id', '=', 'payments.payment_id')
->leftJoin('clients', 'clients.id', '=', 'payments.client_id')
->leftJoin('contacts', 'contacts.client_id', '=', 'clients.id')
->where('payments.account_id', '=', Auth::user()->account_id)
->where('payments.is_deleted', '=', false)
->where('invoices.is_deleted', '=', false)
->where('clients.is_deleted', '=', false)
->where('contacts.deleted_at', '=', null);
when I try to show the result of this query it gives me :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'payments_invoices.invoice_id' in 'on clause' (SQL: select `payments`.`payment_date`, `payments`.`amount`, `invoices`.`public_id`, `invoices`.`invoice_number`, `clients`.`name` as `client_name`, `contacts`.`email`, `contacts`.`first_name`, `contacts`.`last_name`, `clients`.`currency_id`, `clients`.`public_id` as `client_public_id`, `clients`.`user_id` as `client_user_id` from `payments` inner join `invoices` on `invoices`.`id` = `payments_invoices`.`invoice_id` inner join `payments_invoices` on `payments`.`id` = `payments`.`payment_id` left join `clients` on `clients`.`id` = `payments`.`client_id` left join `contacts` on `contacts`.`client_id` = `clients`.`id` where `payments`.`account_id` = 1 and `payments`.`is_deleted` = 0 and `invoices`.`is_deleted` = 0 and `clients`.`is_deleted` = 0 and `contacts`.`deleted_at` is null and `contacts`.`is_primary` = 1 order by `payments`.`payment_date` desc limit 50)
knowing that this query works correctly :
$query = DB::table('payments')
->join('accounts', 'accounts.id', '=', 'payments.account_id')
->join('clients', 'clients.id', '=', 'payments.client_id')
->join('invoices', 'invoices.id', '=', 'payments_invoices.invoice_id')
->join('payments_invoices', 'payments.id', '=', 'payments.payment_id')
})
->leftJoin('payment_types', 'payment_types.id', '=', 'payments.payment_type_id')
->where('clients.is_deleted', '=', false)
->where('payments.is_deleted', '=', false)
->where('invitations.deleted_at', '=', null)
->where('invoices.deleted_at', '=', null)
->where('invitations.contact_id', '=', $contactId)
);
what should I do please ??
This line
->join('payments_invoices', 'payments.id', '=', 'payments.payment_id')
Does not make sense.You try join another table using a field from the table itself.So probably you want to join on payments_invoices.payment_id
Then you can try change the order in which you join the tables
$payments = DB::table('payments')
->join('payments_invoices', 'payments.id', '=', 'payments_invoices.payment_id')
->join('invoices', 'invoices.id', '=', 'payments_invoices.invoice_id')
->leftJoin('clients', 'clients.id', '=', 'payments.client_id')
->leftJoin('contacts', 'contacts.client_id', '=', 'clients.id')
->where('payments.account_id', '=', Auth::user()->account_id)
->where('payments.is_deleted', '=', false)
->where('invoices.is_deleted', '=', false)
->where('clients.is_deleted', '=', false)
->where('contacts.deleted_at', '=', null);
Base from your query:
$payments = DB::table('payments')
->join('invoices', 'invoices.id', '=', 'payments_invoices.invoice_id')
->join('payments_invoices', 'payments.id', '=', 'payments.payment_id')
You are joining payments table to invoices table. And your on clause looks like: ON invoices.id = payments_invoices.invoice_id
But payments_invoices table was joined only on the next line.
Just correct the relation between payments and invoices table (if there is), then it's good.
Since payments and invoices is many-to-many: try this:
DB::table('payments')
->join('payments_invoices', 'payments.id', '=', 'payments_invoices.payment_id')
->join('invoices', 'invoices.id', '=', 'payments_invoices.invoice_id')
In case you have payments_id column on payments_invoices table.