Laravel eloquent join multiple tables in the leftjoin - php

I'm new in laravel. I'm trying to join multiple tables in the left join however i facing the syntax error and i have no idea where goes wrong.
Code
$query = DB::table('sales')
->leftjoin('transactions AS trx', function ($join) {
$join->on('payment_methods AS payment', 'payment.id', '=', 'trx.payment_method_id');
$join->on('transactables', 'transactables.transaction_id', '=', 'transactions.id')
->whereNull('transactions.deleted_at')
->whereNull('transactables.deleted_at')
->where('transactable_type', '=', 'Sale')
->where('transactable_id', '=', 'sales.id');
})
The error meesage
Syntax error near '`payment_methods` as `payment` payment.id `=` and `transactions`.`deleted_at` is'
As the code above you can see. I'm trying to join table payment_methods and transactables within the transactions table.

Why don't you use the Eloquent like
$sales = Sale::with('transactions')->get();
Add relation in Sale model
public function transactions()
{
return $this->morphToMany('App\Transaction', 'transactable');
}
For more info, please refer to Laravel docs

Related

Using multi where queries Laravel relationships

I have two tables (Table1, Table2).
I want to print the sum of the records whose properties match Table1 in Table2 while listing the Table1 table.
My two tables contain very large records, performance is important to me.
// Model -> relationships
public function cars()
{
return $this->hasMany('App\Models\Table2', 'list_id', 'list_id');
}
// Controller
$table1 = Table1::with('cars' => function($query){
$query->where('table2.color','=', 'table1.color')
$query->where('table2.year','=', 'table1.year')
}])
->get();
I'm adding the sample database pictures:
Thank you.
First, add below use statement to the top of your controller:
use DB;
Now, If you only want to get the records amount, you can do this:
$amount = DB::table('table1')
->join('table2', function($join){
$join->on('table1.color', '=', 'table2.color');
$join->on('table1.year', '=', 'table2.year');
})->count();
But if you want to get the list of the table1 records, you can change the query a bit like below:
$records = DB::table('table1')
->select('table1.*')
->join('table2', function($join){
$join->on('table1.color', '=', 'table2.color');
$join->on('table1.year', '=', 'table2.year');
})->count();
Please follow Laravel's official guide on this topic:
https://laravel.com/docs/8.x/queries#advanced-join-clauses
Use join to merge the two tables read more about join here https://www.w3schools.com/sql/sql_join.asp

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

How to build a Laravel query with joins and sum?

I am trying to configure a query within a Laravel app that is equivalent to this:
SELECT SUM(balance), name FROM db.statement_versions
INNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id
GROUP BY name;
This query works when I run it in MySQL Workbench, but when I try to translate it into PHP with the Laravel query builder I am getting an error. What I ultimately want is to return all accounts with their summed balance of statement_versions.balance. Here is my code right now:
public static function query(LensRequest $request, $query)
{
return $request->withOrdering($request->withFilters(
$query->select('accounts.name')->sum('statement_versions.balance')
->join('statements', 'statement_versions.statement_id', '=', 'statements.id')
->join('accounts', 'statements.account_id', '=', 'accounts.id')
->orderBy('balance', 'desc')
->groupBy('statement_versions.balance', 'accounts.name')
));
}
I have tried a couple different variations of this, but I get the error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'statement_versions.balance' in 'field list'. How can I solve this and get the query working correctly?
Not having your tables it will be a bit hard, but I hope that this will give you a path to what you want to achieve, it might be luck that it will work from the first shot :)
DB::table('statement_versions as sv')
->select([
'name',
DB::raw('sum(balance) as total')
])
->join('statements as s', 'sv.statement_id', '=', 's.id')
->join('accounts as a', 's.account_id', '=', 'a.id')
->groupBy('name');

Laravel eloquent query and join on OR condition

I am trying to do an eloquent query where it joins on a table where column a = x OR column b = x; and I cannot get it to work. So I am hoping that someone can help.
Here is my query:
$candidates = HrCandidate::where('people_id', '<>', 'NULL')
->with('contact')
->join(
'people',
->where('id','people_id')
->orWhere('alternate_id','people_id')
)
->get();
I am trying to join with the people table but where people_id = 1 or the alternate_id column. So I am hoping someone can help with this.
To get started, pass a Closure as the second argument into the join method. The Closure will receive a JoinClause object which allows you to specify constraints on the join clause:
$candidates = HrCandidate::join('people', function ($join) {
$join
->on('people.id', '=', 'candidates.people_id')
->orOn('people.alternate_id', '=', 'candidates.people_id');
})
->where('people_id', '<>', 'NULL')
->get();

Complicated Laravel Query leftjoin a made query

Right now I want to have the sum of Sueldo in a column grouped by idEmpleado of table recibo. Im not sure if I can put the DB::table inside the left join. if not how could I call that table in a query to make a join with the information of the empleado.
Here is what I have so far
$pagos = DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftJoin(
DB::table('recibos')
->leftJoin('empleado', 'empleado.idEmpleado', '=', 'recibos.rec_idEmpleado_FK')
->select(DB::raw('idRecibos, rec_idEmpleado_FK, SUM(SueldoBase) as Restante'))
->groupBy('rec_idEmpleado_FK')
->get()
,'recibos', 'recibos.rec_idEmpleado_FK', '=', 'empleado.idEmpleado')
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();
I'm getting an error ErrorException with message :
Array to string conversion
I'm suppose its because I'm trying to make a leftjoin of a query im making there. Dunno Im knid of new to this. Any suggestions ?
With the help of the answer in the commnets I got to this Query,
DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftjoin(
DB::raw('SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
INNER JOIN empleado ON rec_idEmpleado_FK = idEmpleado
GROUP BY rec_idEmpleado_FK'),
function($join)
{
$join->on('idEmpleado', '=', 'rec_idEmpleado_FK');
})
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();
But still get the error:
check the manual that corresponds to your MySQL server version for the right syntax to use near
SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
Any ideas why?
Ok I finally got the answer. I forgot to put the name to the inner query here is my answer. I hope it helps. I based my answer in the link that Chelsea gave me. Thanks
$pagos = DB::table('empleado')
->leftJoin('empresa', 'empresa.idEmpresa', '=', 'empleado.emp_idEmpresa_FK')
->leftJoin('departamento', 'departamento.idDepartamento', '=', 'empleado.emp_idDeparameto_FK')
->leftJoin('tipoperiodo', 'tipoperiodo.idTipoPeriodo', '=', 'empleado.emp_idTipoPeriodo_FK')
->leftjoin(
DB::raw('(SELECT rec_idEmpleado_FK, SUM( SueldoBase ) AS Restante
FROM `recibos`
INNER JOIN empleado ON rec_idEmpleado_FK = idEmpleado
GROUP BY rec_idEmpleado_FK) AS recibos1'),
function($join)
{
$join->on('idEmpleado', '=', 'rec_idEmpleado_FK');
})
->select('idEmpleado', 'Nombre', 'Nombre_Depto', 'Nombre_Empresa', 'Puesto', 'SueldoBase', 'Restante')
->get();

Categories