arithmetic operations in query builder laravel - php

i want to prerform this query in query builder of laravel 5.4
select title, price, price*tauxDiscount/100 as newPrice
from products p, hasdiscount pd, discounts d
WHERE p.idProd = pd.idProd
and d.idDiscount = pd.idDiscount
and now() BETWEEN dateStart and dateEnd
so i write this
$products = DB::table('products')
->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
->select('products.*', '(products.price * discounts.tauxDiscount / 100) as newPrice')
->get();
but he show an this error
[SQLSTATE[42S22]: Column not found: 1054 Unknown column '(products.price
* discounts.tauxDiscount / 100)' in 'field list' (SQL: select
`products`.*, `(products`.`price * discounts`.`tauxDiscount / 100)` as
`newPrice` from `products` inner join `hasDiscount` on
`products`.`idProd` = `hasDiscount`.`idProd` inner join `discounts` on
`discounts`.`idDiscount` = `hasDiscount`.`idDiscount`)][1]

You need to use raw expression like that :
$products = DB::table('products')
->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
->select(DB::raw('products.*,(products.price * discounts.tauxDiscount/100) as newPrice'))
->get();
https://laravel.com/docs/5.4/queries#raw-expressions

Related

Laravel join query not working when passing a variable

I want to execute a join statment in laravel by passing a php varaiable,Bit its not working when passing a varibale. Following is my code
$loc_services = Clinic::select('*')
->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
->join('services', 'services.serviceID', '=', $services_id)
->get();
I tried to execute it as statment and got the following
select * from `clinics` inner join `locations` on `locations`.`clinicID` = `clinics`.`clinicID` inner join `location_services` on `location_services`.`locationID` = `locations`.`locationID` inner join `services` on `services`.`serviceID` = `10`
When i directly executed it in phpmyadmin it returns fllowing error
Column not found: 1054 Unknown column '10' in 'on clause', i found that error is triggering because `10` is inside `''` quotes, how can i execute this
You have to pass $services_id in where cloud not in join on
$loc_services = Clinic::select('*')
->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
->join('services', 'services.serviceID', '=', 'clinics.services_id')//service_id column in Clinic
->where('services.serviceID',$services_id)
->get();
The third parameter in join will be treated as column. If you want to join the column with a specific value, you can use closure like this:
$loc_services = Clinic::select('*')
->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
->join('services', function($join) use ($service_id) {
$join->where('services.serviceID', $service_id);
})
->get();
The Raw sql will be:
inner join `services` on `services`.`serviceID` = 10

Is there a way to convert mysql to laravel eloquent query builder?

I want to obtain the first_check_in and last_check_out of an employee for the current day. The following MySQL code is working good but I am new to eloquent and I do not know how to write it. sorry for my English.
SELECT `employees`.`*`,
`teams`.`description`,
`time_groups`.`start`,
`time_groups`.`end`,
cast(a1.action_time as date) AS date,
Min(`a1`.`action_time`) AS `first_check_in`,
MAX(`a2`.`action_time`) AS `last_check_out`
FROM `employees`
JOIN `teams`
ON `employees`.`team_id` = `teams`.`id`
JOIN `time_groups`
ON `teams`.`time_group_id` = `time_groups`.`id`
JOIN `attendance_employees` AS a1
JOIN `attendance_employees` AS a2
ON `employees`.`id` = `a2`.`employee_id`
AND `a1`.`employee_id` = `a2`.`employee_id`
AND DATE(a1.action_time) = DATE(a2.action_time)
WHERE 1 = 1
AND `a1`.`type` = 1
AND `a2`.`type` = 2
AND DATE(a1.action_time) = CURDATE()
GROUP BY a1.employee_id, `date`
I have try sometime like that
DB::table('employees')
->join('teams', 'employees.team_id', '=', 'teams.id')
->join('time_groups', 'teams.time_group_id', '=', 'time_groups.id')
->join('attendance_employees as a1')
->join('attendance_employees as a2',
function($join) {
$join->on('employees.id', '=', 'a2.employee_id');
$join->on('a1.employee_id', '=', 'a2.employee_id');
$join->on('DATE(a1.action_time)', '=', 'DATE(a2.action_time)');
}
)
->select(
'employees.*',
'teams.description',
'time_groups.start',
'time_groups.end'
)
->addSelect('cast(A1.action_time as date)')->alias('date')
->addSelect('a1.action_time')->alias('check_in')
->addSelect('a2.action_time')->alias('check_out')
->where(1,1)
->where('a1.type', 1)
->where('a2.type', 2)
->groupBy('employee_id')
->groupBy('date')
But getting the following error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'db.attendance_employees as a1' doesn't exist

Laravel query returns column not found

I want to get list of products if they are not exist in my collection. But it returns column not found.
Error
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on clause' (SQL: select * from `products` inner join `collection_products` on `collection_products`.`collection_id` = `1` and `collection_products`.`product_id` != products.id where `products`.`status` = active)
Code
public function edit($id)
{
$collection = Collection::findOrFail($id);
$products = DB::table('products')
->where('products.status', 'active')
->join('collection_products', function ($join) use($id) {
$join->on('collection_products.collection_id', '=', $id)
->where('collection_products.product_id', '!=', 'products.id');
})
->get();
return view('admin.collections.edit', compact('collection', 'products'));
}
Screenshot
collection_products Table
Logic
By query above I should get all products with status of active, except products with id's of 3, 4, 20 because they are already signed to this collection.
Any idea?
Try this query or use it as reference.
$product = DB::table('products')
->join('collection_products','collection_products.product_id','!=','products.id')
->where('products.status', 'active')
->where('collection_products.product_id', '!=', 'products.id')
->where('collection_products.collection_id', '=', $id)
->get();

YEAR(begin_date) unknown column in laravel

SELECT COUNT(*) as count, MONTH(begin_date)
FROM `events`
WHERE (YEAR(begin_date) = YEAR(CURDATE()))
OR (YEAR(begin_date) = YEAR(CURDATE()) + 1)
GROUP BY MONTH(begin_date)
Here is sql query, i want to write it in laravel eloquent.
what i try:
$oncoming_events = DB::table('events')
->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)'))
->where('YEAR(begin_date)', '=', 'YEAR(CURDATE())')
->orWhere('YEAR(begin_date)', '=', 'YEAR(CURDATE()) +1')
->groupBy('MONTH(begin_date)')->get();
Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'YEAR(begin_date)' in 'where clause' (SQL: select count(*) as numOfOncomingEvents, MONTH(begin_date) from events where YEAR(begin_date) =
laravel 5.6
btw
sql query works..
You need to use DB::raw() in where to tell the query builder that it is not column name it is data manipulation in query,
$oncoming_events = DB::table('events')->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)'))->where(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE())')->orWhere(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE()) +1')->groupBy(DB::raw('MONTH(begin_date)'))->get();

Laravel Query Builder join doesn't affect query

I'm trying to build in search functionality in my application (Laravel 5.1), but my join doesn't seem to do anything to the resulting query. What am I doing wrong?
Code:
$query = InvoiceHeader::where('customer_code_id', '=', Auth::user()->customer_code_id);
$query->join('invoice_types', 'invoice_headers.invoice_type_id', '=', 'invoice_types.id')
->where('invoice_types.name', '<>', array_search('Faktura', InvoiceHeader::INVOICE_TYPES));
$invoices = $query->paginate(15);
Resulting query:
select count(*) as aggregate from invoice_headers where customer_code_id = 1 and (invoice_types.name <> 380)
Resulting response:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'invoice_types.name' in 'where clause'
This is the query I was hoping to see:
select count(*) as aggregate
from invoice_headers
inner join invoice_types
on invoice_headers.invoice_type_id = invoice_types.id
where customer_code_id = 1
and (invoice_types.name <> 380)
$query = InvoiceHeader::where('customer_code_id', '=', Auth::user()->customer_code_id);
you need to store the query in a variable.
$query = $query->join('invoice_types', 'invoice_headers.invoice_type_id', '=', 'invoice_types.id')
->where('invoice_types.name', '<>', array_search('Faktura', InvoiceHeader::INVOICE_TYPES));
$invoices = $query->paginate(15);
You need to add JOIN with invoice_types table if you want to filter on invoice_types.name.

Categories