Laravel SQL missing data from Join table - php

I'm using the following code to create a query with a join.
$query = rs_vehicles::select(
'rs_vehicles.id',
'rs_vehicles.type',
'rs_vehicles.make',
'rs_vehicles.model',
'rs_vehicles.year',
'rs_vehicles.status',
'rs_vehicle_regs.registration'
);
$query ->leftJoin('rs_vehicle_regs', function($join){
$join->on('rs_vehicle_regs.rs_vehicles_id', '=', 'rs_vehicles.id')
->where('rs_vehicle_regs.registration_date', '=',
DB::raw("(select max(registration_date) from rs_vehicle_regs where rs_vehicles_id = rs_vehicles.id)"));
});
$rsGrid = $query->get();
This produces the following sql statement:
select rs_vehicles.id, rs_vehicles.type, rs_vehicles.make,
s_vehicles.model, rs_vehicles.year, rs_vehicles.status,
s_vehicle_regs.registration from rs_vehicles
left join rs_vehicle_regs
on rs_vehicle_regs.rs_vehicles_id = rs_vehicles.id
and rs_vehicle_regs.registration_date = (select max(registration_date) from rs_vehicle_regs where rs_vehicles_id = rs_vehicles.id)
The SQL statement generated by Laravel runs perfect when I execute it in MySQL Workbench and it brings back the expected values for ALL fields. However when I execute the code in Laravel although the script runs perfectly with no errors and brings back almost all the required data the 'rs_vehicle_regs.registration' field which is in the joined table comes back as null. I've spent ages trying to figure this out and I am getting nowhere. Anybody any idea why this wont work in Laravel? I'm at my wits end.
I have tried changing get() to toSql() and I get the following
select `rs_vehicles`.`id`, `rs_vehicles`.`type`, `rs_vehicles`.`make`, `rs_vehicles`.`model`, `rs_vehicles`.`year`, `rs_vehicles`.`vehicle_status`, `vh_type`.`display_text` as `type_text`, `vh_status`.`display_text` as `vehicle_status_text`, `rs_vehicle_regs`.`registration` as `registration` from `rs_vehicles` left join `app_params` as `vh_type` on `rs_vehicles`.`type` = `vh_type`.`list_value` and `vh_type`.`param_type` = ? left join `app_params` as `vh_status` on `rs_vehicles`.`vehicle_status` = `vh_status`.`list_value` and `vh_status`.`param_type` = ? left join `rs_vehicle_regs` on `rs_vehicle_regs`.`rs_vehicles_id` = `rs_vehicles`.`id` where `rs_vehicles`.`status` = ?
I have also tried the following:
$query ->leftJoin('rs_vehicle_regs', function($join){
$join->on('rs_vehicle_regs.rs_vehicles_id', '=', 'rs_employees.rs_vehicles_id')
->where('rs_vehicle_regs.registration_date', '=', 'max(registration_date)');
});
This produces the exact same result as the original query where the object as the field but the values are null.
Then I tried this:
$query ->leftJoin('rs_vehicle_regs', 'rs_vehicle_regs.rs_vehicles_id', '=', 'rs_vehicles.id');
This join works and brings back the data I am looking for however if the join table has more than one entry related to the parent table as can happen I get all records returned and I only want one record were max(registration_date). This has me totally stumped.

Related

Laravel Join query

I'm new to Laravel, I wanted to make a union with the DB and it didn't work for me, I tried it in SQL and it worked fine, I don't know what I'm doing wrong?
Would you be kind enough to help me with this dilemma, thanks
here is the SQL query:
SELECT SUM(materias.Credito) FROM historico_notas INNER JOIN materias ON materias.id = historico_notas.materias_id INNER JOIN estudiante_seccion on estudiante_seccion.id = historico_notas.estudiante_seccion_id WHERE historico_notas.nota >= 10 and estudiante_seccion.id_persona = 627;
This is the generated query SQL:
here in my attempt in laravel:
$prueba = DB::table('historico_notas')
->join('materias','materias.id', '=',' historico_notas.materias_id ' )
->join('estudiante_seccion',' estudiante_seccion.id','=','historico_notas.estudiante_seccion_id' )
->where('historico_notas.nota','>=',10 )
->where(' estudiante_seccion.id_persona','=',$persona_alumno)
->sum('materias.Credito');
This is the generated query and error.
My dilemma is that I want my sql query to Laravel and something gives me an error and I don't know what error I have
the SQL query works perfectly for me, but when I try to go to Laravel it gives me an error,
what i show is my attempt to pass the sql query to laravel and what i want is my sql query to laravel
How would the syntax be properly?
I just converted your SQL into this.
$query = DB::table('historico_notas')
->join('materias', 'materias.id', '=', 'historico_notas.materias_id')
->join('estudiante_seccion', 'estudiante_seccion.id', '=', 'historico_notas.estudiante_seccion_id')
->where('historico_notas.nota', '>=', 10)
->where('estudiante_seccion.id_persona', '=', 627)
->sum('materias.Credito');
The error gets an unknown column "historico_notas.nota", you can check it in the table if it exists

laravel - correct query work in phpmyadmin, return null in app

I have this code:
$abcd= DB::table('control')
->leftJoin('proces', 'proces.id_control', '=', 'control.id_control')
->select('control.id_risk', DB::raw("group_concat(proces.id_procedur) as prc"))
->where('control.id_theme', '=', $id)
->whereExists(function ($query) {
$query->select('id_control')
->from('proces') ->where('control.id_control','proces.id_control');
})
->groupBy('control.id_risk')
->get();
This query work perfectly, when i wrote it in phpmyadmin, but when I try to execute it in app query return empty array. Where is problem
UPDATE
After i check how looks query from laravel there is one wrong
select `control`.`id_risk`, group_concat(proces.id_procedur) as prc from `control` left join `proces` on `proces`.`id_control` = `control`.`id_control` where `control`.`id_theme` = ? and exists (select `id_control` from `proces` where `control`.`id_control` = ?) group by `control`.`id_control`
First question mark is corrent beacue this $id(by the way variable is passing good value) but the second question mark should not be there.

How to create SQL Join Statement in Laravel Controller

I have two table customer_id namely tbl_customer and tbl_stocks connected on the same database. My logic about this problem is JOIN sql statement.
This is for Laravel and MySQL, so far i've tried this on PHP and is working fine but when I implement it on laravel it is not working i wonder why?
here is my code in PHP and want to convert it to laravel but I dont know where to put? will i put it in the View or in the Controller
$query = "SELECT c.*, s.* FROM tbl_customer c JOIN tbl_stock s ON s.customer_id = c.customer_id AND c.customer_id = 1";
Controller
$data = DB::table('tbl_customer')
->join ...... //Im not sure about this
->select .... // neither this
->get();
print_r($data)
Model
I have no codes on my model
Routes
Route::get('/admin/shopcontrol', 'Admin\ShopsController#testquery');
I expect a result of fetching or getting the query or result of the values in just a simple echo and the fetch join is connected
Have you checked the Laravel site?
https://laravel.com/docs/5.7/queries#joins
It has a demonstration you could use to reorganize your code.
As it follows below from the site.
Joins
Inner Join Clause
The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Of course, as you can see, you can join to multiple tables in a single query:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
You may find more information there if it suits you.
Try this:
$data = DB::table('tbl_customer')
->join('tbl_stock', 'customer_id', '=', 'tbl_customer.customer_id')
->select('tbl_customer.*', 'tbl_stock.*')
->where('customer_id', '=', 1)
->get();

CodeIgniter how to sort joined record

I have following query in CodeIgniter:
$user = $this->db
->select('users.*, login_logs.ip_address, login_logs.date, login_logs.userid')
->from('db.users')
->join('db.login_logs', 'users.userid = login_logs.userid')
->group_by('users.userid')
->get()
->result_array();
It works very good but I have to select last record for each user( in login_logs table) but now I'm getting first record.
I have tried :
->order_by('login_logs.idlogin_logs', 'DESC')
but it didn't work.
I have no idea how to do it.
Is there any easy way to reach it?
#edit
I have triend ASC/DESC. No changes.
Present query:
SELECT `users`.*, `login_logs`.`ip_address`, `login_logs`.`date`, `login_logs`.`userid`
FROM `db`.`users`
JOIN `db`.`login_logs` ON `users`.`userid` = `login_logs`.`userid`
GROUP BY `users`.`userid`

Codeigniter Active Record / MySQL Join Query - How to Return Results if one of the Table Rows is Not Present

I have the following query:
$this->db
->select('SQL_CALC_FOUND_ROWS null as rows
,table1.*
,table2.*
,table3.*', FALSE)
->from('table1')
->where('table1.column1', $user_id)
->join('table2', 'table2.column2 = table1.column2')
->join('table3', 'table3.column2 = table1.column2')
->group_by('table1.column2')
->order_by('table1.column2', 'DESC');
$query = $this->db->get();
The problem is, there may not be a row in table 3 and if there is not, I would still like to return a result with the remainder of the query data. Please could someone advise how to achieve this?
you should do a left join on table3
Use left join and also use group_by to get exact records:
$this->db->join('login_ranknames AS t4', 't4.id = t1.rank', 'left');
$this->db->group_by('t4.id');

Categories