How can I solve this error in my Laravel model? - php

Here's my code.
The database name is socapa.
class Student extends Model
{
...
public static function rsStuds(
$varSession_rsStuds,
$varCampus_rsStuds,
$varProgram_rsStuds,
$varSeason_rsStuds,
$startRow_rsStuds,
$maxRows_rsStuds) {
return Student::select(
'contacts.FirstName',
'contacts.LastName',
'contacts.ContactID',
'students.StudentID',
'registrations.CourseID',
'registrations.RegDate',
'contacts.City',
'contacts.State',
'contacts.Country',
'campuses.CampusName',
'programs.ProgramName',
'courses.SessionID',
'courses.CourseName',
'courses.Season',
'students.StudentID',
'programs.ProgramID',
'sessions.SessionID',
'sessions.SessionName',
'programs.ProgramName')
->join('registrations', 'students.StudentID', '=', 'registrations.StudentID')
->join('contacts', 'contacts.ContactID', '=', 'students.StudentContactID')
->join('courses', 'courses.CourseID','=', 'registrations.CourseID')
->join('campuses', 'campuses.CampusID', '=', 'courses.CampusID')
->join('programs', 'programs.ProgramID', '=', 'courses.ProgramID')
->join('sessions', 'sessions.SessionID', '=', 'courses.SessionID')
->where('courses.SessionID', 'LIKE', "%".$varSession_rsStuds."%")
->where('courses.CampusID', 'LIKE', "%".$varCampus_rsStuds."%")
->where('courses.ProgramID', 'LIKE', "%".$varProgram_rsStuds."%")
->where('courses.Season', '=', ''.$varSeason_rsStuds)
->groupBy('courses.ProgramID')
->orderBy('contacts.LastName')
->skip(''.$startRow_rsStuds)
->take(''.$maxRows_rsStuds)->get();
}
...
}
When I run the project, the error following bellow, appears.
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1055 'socapa.contacts.FirstName' isn't in GROUP BY (SQL: select contacts.FirstName, contacts.LastName, contacts.ContactID, students.StudentID, registrations.CourseID, registrations.RegDate, contacts.City, contacts.State, contacts.Country, campuses.CampusName, programs.ProgramName, courses.SessionID, courses.CourseName, courses.Season, students.StudentID, programs.ProgramID, sessions.SessionID, sessions.SessionName, programs.ProgramName from students inner join registrations on students.StudentID = registrations.StudentID inner join contacts on contacts.ContactID = students.StudentContactID inner join courses on courses.CourseID = registrations.CourseID inner join campuses on campuses.CampusID = courses.CampusID inner join programs on programs.ProgramID = courses.ProgramID inner join sessions on sessions.SessionID = courses.SessionID where courses.SessionID LIKE %1% and courses.CampusID LIKE %1% and courses.ProgramID LIKE %1% and courses.Season = -1 group by courses.ProgramID order by contacts.LastName asc limit 50 offset 0)

Go to the config folder and open database.php find mysql and change
'strict' => false,

Related

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

How Get Count in Join Query in Laravel

I want to convert the following SQL to Laravel.
SELECT COUNT('uc.*') AS count_down, bs.brand_name
FROM `user_activities` AS uc
JOIN brands AS bs ON uc.brand_id = bs.id
GROUP BY uc.brand_id
ORDER BY count_down DESC
LIMIT 5
But when doing this:
$top_donwload_list = DB::table('user_activities')
->leftJoin('brands', 'brands.id', '=', 'user_activities.brand_id')
->selectRaw('brands.*, brands.brand_name, brands.id, count(user_activities.action_type) as user_activitiesCount')
->groupBy('user_activities.brand_id')
->get();
I get this error:
SQLSTATE[42000]: Syntax error or access violation: 1055 'colorworld.brands.id' isn't in GROUP BY (SQL: select brands.*, brands.brand_name, brands.id, count(user_activities.action_type) as user_activitiesCount from user_activities left join brands on brands.id = user_activities.brand_id group by user_activities.brand_id)
I tried to set 'strict' => true, in database.php but I get the same error in Laravel 5.7.
Update:- database table
If I understood your question correctly, you are trying to find the count of user activities grouped by a brand's name. Also you want the top 5 records ordered by the ones with the most user activities.
So, the following should work:
$top_donwload_list = DB::table('user_activities')
->selectRaw("brands.brand_name, COUNT('user_activities.*') as user_activitiesCount")
->join('brands', 'brands.id', '=', 'user_activities.brand_id')
->groupBy('brands.brand_name')
->orderBy('user_activitiesCount', 'desc')
->take(5)
->get();
You can use Laravel Eloquent. I Assume that the relationship between brand and user_activities is one to many and Here, the "Brand" is the model of the brand entity.
$count = Brand::leftJoin
('user_activities', function($join_brands){
$join_brands-> on
('brands.id', '=','user_activity.brand_id');
)->orderBy('user_activities.count_down','desc ')
->groupBy('user_activities.brand_id')->count();

How to effectively using laravel 5.5 eloquent on complex join and group

I have this query that successfully run on mysql workbench:
SELECT
any_value(u.username),
any_value(b.name),
any_value(gc.visit_cycle_id),
any_value(gc.group_number),
any_value(dc.total_customer),
count(*) as total_day
FROM
trackgobackenddb.group_cycles gc
LEFT JOIN (
SELECT
any_value(dc.group_cycle_id) as group_cycle_id,
count(*) as total_customer
FROM
trackgobackenddb.destination_cycles dc
GROUP BY dc.group_cycle_id
) dc ON dc.group_cycle_id = gc.id
LEFT JOIN visit_cycles vc ON gc.visit_cycle_id = vc.id
LEFT JOIN users u ON vc.user_id = u.id
LEFT JOIN branches b ON vc.branch_id = b.id
GROUP BY gc.visit_cycle_id, gc.group_number;
How to convert that query so I can use laravel eloquent or query builder?
You can use DB::select to run complex raw SQL
$sql = "";
$data = DB::select($sql);
Here's my untested attempt using the query builder:
DB::table('group_cycles AS gc')
->leftJoin('destination_cycles AS dc', function ($join) {
$join->on('dc.group_cycle_id', '=', 'gc.id')
->select(['dc.group_cycle_id AS group_cycle_id', DB::raw('select count(*) AS total_customer')]);
})
->leftJoin('visit_cycles AS vc', function ($join) {
$join->on('gc.visit_cycle_id', '=', 'vc.id');
})
->leftJoin('users AS u', function ($join) {
$join->on('vc.user_id', '=', 'u.id');
})
->leftJoin('branches AS b', function ($join) {
$join->on('vc.branch_id', '=', 'b.id');
})
->groupBy('gc.visit_cycle_id', 'gc.group_number')
->get();

Laravel Join multiple table not working

I'm having an issue on Laravel 5.4 when I try to use only one join it works ok and returns correct data, but their add another join it doesn't work.
$data = Player::select(DB::raw('CONCAT(familyName,", ",firstName) AS fullName'))
->where('firstname', 'like', '%'.$search.'%')
->orWhere('familyName', 'like', '%'.$search.'%')
->orderBy('familyName', 'asc')
->join('teams', 'players.primaryClubId', '=', 'teams.clubId')
->join('person_competition_statistics', 'players.personId', '=', 'person_competition_statistics.personId')
->addSelect(['players.*', 'teams.teamName', 'teams.teamNickname', 'teams.teamCode'])
->get()
->unique() //remove duplicates
->groupBy(function($item, $key) { //group familyName that starts in same letter
return substr($item['familyName'], 0, 1);
})
->map(function ($subCollection) {
return $subCollection->chunk(4); // put your group size
});
return $data;
Returned Error:
QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'familyName' in field list is ambiguous (SQL: select CONCAT(familyName,", ",firstName) AS fullName, `players`.*, `teams`.`teamName`, `teams`.`teamNickname`, `teams`.`teamCode` from `players` inner join `teams` on `players`.`primaryClubId` = `teams`.`clubId` inner join `person_competition_statistics` on `players`.`personId` = `person_competition_statistics`.`personId` where `firstname` like %% or `familyName` like %% order by `familyName` asc)
If you are joining table then you should give table alias. like team as t , players as p and then column name like p.playername

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