Cannot retrieve column using eloquent - mysql

I have a query that extracts student marks, but I want to also extract the name and surname of the student but I get the error
SQLSTATE[42000]: Syntax error or access violation: 1055 'shunifu_db.users.name' isn't in GROUP BY (SQL: select name, marks.student_id,ROUND(AVG(mark)) as mark from grades inner join grades_students on grades_students.grade_id = grades.id inner join users on grades_students.student_id = users.id inner join marks on marks.student_id = grades_students.student_id where grades.stream_id = 5 and assessement_id = 1 group by marks.student_id)
here is my code
$result = DB::table('grades')
->join('grades_students', 'grades_students.grade_id', '=', 'grades.id')
->join('users','grades_students.student_id','=','users.id')
->join('marks','marks.student_id','=','grades_students.student_id')
->where('grades.stream_id', $request->stream_name)
->where('assessement_id',$request->assessement)
->select(DB::raw('marks.student_id,ROUND(AVG(mark)) as mark'))
->groupBy('marks.student_id')
->get()

May be it will work
$result = DB::table('grades')
->join('grades_students', 'grades_students.grade_id', '=', 'grades.id')
->join('users','grades_students.student_id','=','users.id')
->join('marks','marks.student_id','=','grades_students.student_id')
->where('grades.stream_id', $request->stream_name)
->where('assessement_id',$request->assessement)
->select(DB::raw('users.id,users.name,ROUND(AVG(mark)) as mark'))
->groupBy(['users.id', 'users.name'])
->get()
Here I'm using user table for grouping and also fetching name.

Related

Convert GROUP_CONCAT in SQL Query into Laravel Query?

this is my SQL query:
SELECT pendaftaran.id_pendaftaran,
pendaftaran.nama,
pendaftaran.nim,
pilihan_daftar.id_pilihan,
pilihan_daftar.alasan_pil,
Group_concat(dinas_biro.nama_dinasbiro) AS nama_dinas
FROM pendaftaran
JOIN pilihan_daftar
ON pendaftaran.id_pendaftaran = pilihan_daftar.id_pendaftaran
JOIN dinas_biro
ON dinas_biro.id_dinasbiro = pilihan_daftar.id_pilihan
GROUP BY pendaftaran.id_pendaftaran;
then, i convert into laravel query:
Pendaftaran::join('pilihan_daftar','pendaftaran.id_pendaftaran','=','pilihan_daftar.id_pendaftaran')
->join('dinas_biro','dinas_biro.id_dinasbiro','=','pilihan_daftar.id_pilihan')
->select(
'pendaftaran.id_pendaftaran',
'pendaftaran.nama',
'pendaftaran.nim',
'pilihan_daftar.id_pilihan',
'pilihan_daftar.alasan_pil',
DB::raw('GROUP_CONCAT(dinas_biro.nama_dinasbiro) as nama_dinas')
)
->groupBy('pendaftaran.id_pendaftaran')
->get();
But error:
SQLSTATE[42000]: Syntax error or access violation: 1055
'keanggotaan_bem.pendaftaran.nama' isn't in GROUP BY (SQL: select
pendaftaran.id_pendaftaran, pendaftaran.nama,
pendaftaran.nim, pilihan_daftar.id_pilihan,
pilihan_daftar.alasan_pil, GROUP_CONCAT(dinas_biro.nama_dinasbiro)
as nama_dinas from pendaftaran inner join pilihan_daftar on
pendaftaran.id_pendaftaran = pilihan_daftar.id_pendaftaran
inner join dinas_biro on dinas_biro.id_dinasbiro =
pilihan_daftar.id_pilihan group by pendaftaran.id_pendaftaran)
Can someone help me :(

LARAVEL, ELOQUENT, SQL - groupBy 1

When I run the below SQL manually I get my expected results. I am trying to write the same query in Laravel's Eloquent and I get an error:
SQLSTATE[42000]: Syntax error or access violation: 1056 Can't group on 'aggregate' (SQL: select count() as aggregate from daily_menu inner join meals on daily_menu.id = meals.daily_menu_id left join fruits on fruits.meal_id = meals.id where lodge_id = 1 group by 1)*
The original SQL Query that works:
SELECT
d.id,
SUM(IF(f.id IS NULL, 0, 1)) AS fruit_count
FROM daily_menu d
JOIN meals m
ON d.id = m.daily_menu_id
LEFT JOIN fruits f
ON m.id = f.meal_id
GROUP BY 1
My Laravel Eloquent Implementation:
$query = $query
->select("daily_menu.id", DB::raw("SUM(IF(fruits.id IS NULL, 0, 1)) AS fruit_count"))
->join("meals", "daily_menu.id", "=", "meals.daily_menu_id")
->leftJoin("fruits", "fruits.meal_id", "=", "meals.id")
->groupBy(DB::raw("1"));
$query = $query
->select("daily_menu.id", DB::raw("SUM(IF(fruits.id IS NULL, 0, 1)) AS fruit_count"))
->join("meals", "daily_menu.id", "=", "meals.daily_menu_id")
->leftJoin("fruits", "fruits.meal_id", "=", "meals.id")
->groupBy(DB::raw("daily_menu.id"));
I shouldn't have used 1 I should have used the proper column alias.
Related: Can't fix this: "Cannot group by an aggregate"

How to join with three rows from table one with second table in laravel

in laravel 5.6 i want to fetch data from database with join query in my case i want to join multiple tables such as employee, designation, booking, vehicles when i use join it shows following errors(SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'employees' (SQL: select * from bookings inner join vehicles on bookings.vehicle_id = vehicles.vehicle_id inner join employees on bookings.driver_id = employees.id inner join employees on bookings.conductor_id = employees.id inner join employees on bookings.helper_id = employees.id inner join designations on employees.desg_id = designations.desc_id)) i google it several times but i could not find any solutions how can i solve this problems your efforts will be appreciate in this case thanks in advance.
in my laravel model Booking
public function get_booking(){
$booking = DB::table('bookings')
->join('vehicles', 'bookings.vehicle_id', '=', 'vehicles.vehicle_id')
->join('employees', 'bookings.driver_id', '=', 'employees.id')
->join('employees', 'bookings.conductor_id', '=', 'employees.id')
->join('employees', 'bookings.helper_id', '=', 'employees.id')
->join('designations', 'employees.desg_id', '=','designations.desc_id')
->get();
return $booking;
You have to use table aliases and join designations three times:
->join('employees as e1', 'bookings.driver_id', '=', 'e1.id')
->join('employees as e2', 'bookings.conductor_id', '=', 'e2.id')
->join('employees as e3', 'bookings.helper_id', '=', 'e3.id')
->join('designations as d1', 'e1.desg_id', '=','d1.desc_id') -
->join('designations as d2', 'e2.desg_id', '=','d2.desc_id')
->join('designations as d3', 'e3.desg_id', '=','d3.desc_id')
You also have to use column aliases (depending on your required columns):
->get(['bookings.*', 'vehicles.*', 'e1.name as driver_name',
'e2.name as conductor_name', 'e3.name as helper_name']);

Yii CDbCriteria add column

I created a criteria:
$ids = array(1,2,3);
$criteria = new CDbCriteria;
$criteria->select = 'SUM(quantity) as quan';
$criteria->with = array('order');
$criteria->condition="order.customer = ".Yii::app()->user->id." AND order.status_id <> 4 AND order.status_id <> 3 AND order.type = 0";
$criteria->addInCondition("product_id", $ids);
$order_prod = OrderProduct::model()->find($criteria);
but when i run this i got error:
1140 In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'als.t.id'; this is incompatible with sql_mode=only_full_group_by. The SQL statement executed was: SELECT SUM(quantity) as quan, t.id AS t0_c0, order.id AS t1_c0, order.phone AS t1_c1, order.email AS t1_c2.
In criteria select i use only sum of quantity.
Hi Disable only_full_group_by
try this sql
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));
You want to get only quantity sum from OrderProduct table. So, it'll be better not to use active record, but write simple command with query, something like this:
$result = Yii::app()->db->createCommand('
SELECT SUM(t.quantity) as quan
FROM order_product t
LEFT JOIN order ON order.ID = t.order_id
WHERE
order.customer = :userId AND
order.status_id NOT IN (3,4) AND
order.type = 0 AND
t.product_id IN (1,2,3)
')->queryScalar([
':userId' => Yii::app()->user->id,
]);
Here "db" is the name of your CDbConnection component. OrderProduct table name and join condition may be different in your system.

how to select last 5 records from the my sql table

I am getting data from the server. I want that user may get only the last 5 records in the tables.
Here is the query I am currently using; it is not working:
$query = mysql_query("
SELECT
ml.PostID,
ml.UserID,
ml.PostDate,
ml.PostTime,
ml.PostCategory,
ml.PostSubCategory,
ml.PostComments,
cat.UserName
FROM UserPosts AS ml
LEFT JOIN UserNames cat
ON cat.UserID = ml.UserID
ORDERD BY DESC LIMIT 5");
Gives following error
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/content/i/h/u/ihus235/html/cs/pah_brd_v1/productivo/getPosts.php on line 77
add column name in order by clause
SELECT ml.PostID,
ml.UserID,
ml.PostDate,
ml.PostTime,
ml.PostCategory,
ml.PostSubCategory,
ml.PostComments,
cat.UserName
FROM UserPosts AS ml
LEFT JOIN UserNames cat
ON cat.UserID = ml.UserID
ORDER BY ml.PostComments DESC
LIMIT 5
$sql = 'SELECT ml.PostID,
ml.UserID,
ml.PostDate,
ml.PostTime,
ml.PostCategory,
ml.PostSubCategory,
ml.PostComments,
cat.UserName
FROM UserPosts AS ml
LEFT JOIN UserNames cat
ON cat.UserID = ml.UserID
ORDER BY ml.PostTime DESC LIMIT 5';
$query = mysql_query($sql) or die(mysql_error());
Try this.