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)"))
Related
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 have a query where I want to order by shipping_date but I get this error:
QueryException in Connection.php line 770:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression 1 of
ORDER BY clause is not in GROUP BY clause and contains nonaggregated
column 'device.devices.shipping_date' which is not functionally
dependent on columns in GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by (SQL: select count(*) as device,
DATE_FORMAT(shipping_date,"%M %Y") as year from `devices` where
`shipping_date` is not null and `internal_use` = 0 group by `year` order by `shipping_date` asc)
My code:
$sold_devices = Device::selectRaw('count(*) as device, DATE_FORMAT(shipping_date,"%M %Y") as year')
->whereNotNull('shipping_date')
->where('internal_use', '=', 0)
->groupBy('year')
->orderBy('shipping_date', 'asc')
->pluck('device', 'year');
any help?
Thanks
You have to specify the exact select column in your group by: in your case
->groupBy('DATE_FORMAT(shipping_date,"%M %Y")')
->orderBy('DATE_FORMAT(shipping_date,"%M %Y")', 'asc')
Generally speaking, you can't use column aliases in where, group by and order by clauses.
Edit
To change the ordering criteria you can use the numeric value of the month instead of its name:
->groupBy('DATE_FORMAT(shipping_date,"%M %Y")')
->orderBy('DATE_FORMAT(shipping_date,"%Y%c")', 'asc')
let's try this.
it will work...
->groupBy(DB::raw('DATE_FORMAT(shipping_date,"%M %Y")'))
->orderBy(DB::raw('DATE_FORMAT(shipping_date,"%M %Y"))','asc')
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.
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?
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