Laravel 5 SQLSTATE[42S22]: Column not found - php

I am doing some joins and trying to get the data. My query builder is:
$datasource = DB::table('vehicles')->join('brands', 'vehicles.brand_id', '=', 'brands.id')->join('sections', 'vehicles.section_id', '=', 'sections.id')->select('vehicles.*, vehicles.id AS vid');
But i am getting this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'vehicles.model,' in 'field list' (SQL: select vehicles.model, as
AS from vehicles inner join brands on vehicles.brand_id =
brands.id inner join sections on vehicles.section_id =
sections.id limit 4 offset 0) Line 620
What i am doing wrong ?

You should use selectRaw() instead of select():
->selectRaw('vehicles.*, vehicles.id AS vid');
Read more about raw expressions: http://laravel.com/docs/5.0/queries#raw-expressions

Related

How to aggregate query on related table's field in Laravel?

I have a One To Many (Inverse) relation on my laravel 5.4 application. There are two models Sale and Vehicle which are related and associated with the scene.
The relation on the Sale model is :
public function vehicle()
{
return $this->belongsTo('App\Models\Vehicle','vehicle_id');
}
Table sales has following fields :
id, vehicle_id, date_time, status etc.
Table vehicles has following fields :
id, reg_number, volume, status etc.
What I want is, sum of the field 'vehicles.volume' of Sale records within the search conditions.
I have tried some methods like the following one:
$query = Sale::where('status', 1);
$query = $query->where('date_time', '<', "2017-05-10 10:10:05");
$totalVolume = $query->whereHas('vehicle')->sum('vehicles.volume');
and it resulted in the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'vehicles.volume' in 'field list' (SQL: select
sum(vehicles.volume) as aggregate from sales where status = 1
and date_time < "2017-05-10 10:10:05" and exists (select * from vehicles where sales.vehicle_id =
vehicles.id))
hopefully waiting for a solution to 'get the sum of the volume of the sales' using eloquent query.
Edited
You need to use a join before summing the vehicles.volume column
$totalVolume = Sale::where('status', 1)
->where('date_time', '<', "2017-05-10 10:10:05")
->join('vehicles', 'vehicles.id', '=', 'sales.vehicle_id')
->select(DB::raw('sum(vehicles.volume) as total_volume');
select sum(volume) as aggregate from vehicles INNER JOIN sales ON vehicles.id=sales.vehicle_id

I found Error in query when i join with another table

When i join one table to another then i got this error. i put as keyword but its not working it give me error like field not found how can i solve this error
Code:
Product::leftjoin('reviews','products.id','=','reviews.productID')
->select(array('products.*',
DB::raw('AVG(rating) as ratings_average')
))
->where(function($query) use ($categoriesID,$brands,$priceArray,$ratingArray)
{
$query->whereIn('categoryID',$categoriesID);
if(count($brands) > 0)
{
$query->whereIn('brandID',$brands);
}
$query->whereBetween('productSellingPrice',$priceArray);
if(count($ratingArray) > 0)
{
$query->whereBetween('ratings_average',$ratingArray);
}
})
->groupBy('products.id')
->get();
Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ratings_average' in 'where clause' (SQL: select `products`.*, AVG(rating) as ratings_average from `products` left join `reviews` on `products`.`id` = `reviews`.`productID` where (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000 and `ratings_average` between 1 and 2) group by `products`.`id`)
Instead of rating array you can find out $minRating and maxRating. By these two value you can run you query like this:
$query->whereBetween('rating',[$minRating,$maxRtaing]);
The problem is a SQL problem, and it has to do with scoping. I'm not well versed in laravel's API, but the SQL generated (based on your helpful error message) is:
select `products`.*, AVG(rating) as ratings_average
from `products` left join `reviews` on `products`.`id` = `reviews`.`productID`
where (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000
and `ratings_average` between 1 and 2) group by `products`.`id`)
The problem is that the ratings_average calculated column belongs to the GROUP BY scope. The only way to reference that column is in a HAVING statement. Your SQL statement would look like this:
select `products`.*, AVG(`ratings`.`rating`) as ratings_average
where `products`.`id` = `reviews`.`productId`
group by `products`.`id`
having (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000
and `ratings_average` between 1 and 2)
Technically speaking, the first two clauses in the having statement above could be in your WHERE clause, but the ratings_average named column can only be referenced in the HAVING clause. Both WHERE and HAVING restrict your results, but HAVING is evaluated after the grouping took place.

Laravel groudby use day()

my sql is
select * from patient group by day(created_at) order by created_at"
but my use laravel ,i think use Model
Patient_Model::groupBy("DAY(created_at)")
->orderBy("created_at","desc")
->get();
this is error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'DAY(created_at)' in 'group statement' (SQL: select * from `patients` group by `DAY(created_at)` order by `created_at` desc)
How uese day() in laravel5.1?
You should be able to use it with DB::raw() like so :
Patient_Model::
->groupBy(DB::raw('DAY(created_at)'))
->orderBy("created_at","desc")
->get();
Use this instead
groupBy(\DB::raw("DAY(created_at)"))

Wrong SQL query generated by Doctrine2 Paginator

My scripts stop working after I've upgraded from Doctrine 2.3.6 up to Doctrine 2.5.0 .
I want to perform query with pagination on joined tables. I have two entities: Program and ProgramVersion joined by Program::versions field.
Here is the query:
$query = $em->createQuery('
SELECT m, v
FROM Entity\Program m
LEFT JOIN m.versions v
WITH m.version = v.version
WHERE m.deletedDate IS NULL
ORDER BY m.type asc');
Then I pass the query to Paginator
$pResult = new \Doctrine\ORM\Tools\Pagination\Paginator($query, true);
At the stage when I do $pResult->getIterator() I get the following error message:
An exception occurred while executing '
SELECT DISTINCT id_0
FROM (
SELECT e0_.id AS id_0, e1_.id AS id_27 /* removed a lot of fields here */ FROM entity_program e0_
LEFT JOIN entity_program_version e1_ ON e0_.id = e1_.master_id AND (e0_.version = e1_.version)
WHERE e0_.deleted_date IS NULL
) dctrn_result ORDER BY e0_.type_id ASC':
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'e0_.type_id' in 'order clause'
Obviously the SQL is wrong. The ORDER BY clause is outside of the main SELECT and it contains the field which doesn't exist.
Can anybody help me to solve the issue?

Unknown column 't.faic' in 'field list'

When I execute my query i got an error
[Err] 1054 - Unknown column 't.faid' in 'field list'
I have a table called
app_interview with fields 'atid','atic','atname','inttotal'
applicants with the same atic are just one person.
I want to total all the total of applicant with same atic field value and divide it with 7 and save the average score to a new table called:
afnup_worksheet with field 'faid','faic','fnl_name','ftotal'
heres my current query:
INSERT INTO afnup_worksheet (faid,faic,fnl_name,ftotal)
SELECT DISTINCT
t.faid
,t.faic
,t.fnl_name
,(SELECT SUM(t2.inttotal) FROM app_interview t2 WHERE t2.atic = t.faic)/7 thissum
FROM app_interview t
GROUP BY atname HAVING COUNT(DISTINCT atic)=1
You.re selecting t.faic, where t refers to app_interview, but according to the details you have posted, app_interview doesn't conatin a field called faic. This is also true for t.faid and t.fnl_name.
According to your description, app_interview does not have a faid column

Categories