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

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

Related

How can I solve this error in my Laravel model?

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,

Laravel 7: getting rows between two dates where the column is datetime

I'm having trouble building an eloquent query wherein I can recreate this sql command:
The date_created column is datetime.
SELECT * FROM covidchecklist cc
LEFT JOIN patient_appointment pa ON cc.appointment_id = pa.appointment_id
LEFT JOIN users pat ON pa.user_id = pat.id
WHERE DATE_FORMAT(cc.date_created,'%Y-%m-%d') BETWEEN '2021-01-27' AND '2021-01-27'
What I have right now:
CovidChecklist::
leftJoin('patient_appointment', 'covidchecklist.appointment_id', '=', 'patient_appointment.appointment_id')
->leftJoin('users as patient', 'patient_appointment.user_id', '=', 'patient.id')
->whereRaw(' DATE_FORMAT(covidchecklist.date_created,"%Y-%m-%d") BETWEEN '.'$this->date_from'.' AND '.'$this->date_to'.' ')
->select(
*select stuff*
)
->get();
I am using whereRaw since I can't get this to work:
->whereBetween('covidchecklist.date_created', [$this->date_from, $this->date_to])
Try this, mate
->whereBetween(\DB::raw('DATE_FORMAT(covidchecklist.date_created,"%Y-%m-%d")'), [$this->date_from, $this->date_to])

Create subquery in NOT IN

I am using Laravel Framework 6.16.0.
I have the following sql query:
SELECT DISTINCT
`companies`.*
FROM
`companies`
LEFT JOIN `trx` ON `trx`.`companies_id` = `companies`.`id`
WHERE
`trx`.`transaction_date` >= 2020-11-12 AND companies.symbol NOT IN (SELECT DISTINCT
companies.symbol
FROM
`companies`
LEFT JOIN articles a ON a.companies_id = companies.id
WHERE
a.created_at >= 2020-11-12
ORDER BY
created_at
DESC)
ORDER BY
transaction_date
DESC
I have created the following eloquent query:
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', Carbon::today()->subDays(1)->startOfDay())
->orderBy('transaction_date', 'desc')
->distinct()
->get('symbol');
However, I am not sure how to pack the in my eloquent query to get all the symbol back that should be excluded.
I highly appreciate your replies!
You should try something like this:
$date = Carbon::today()->subDays(1)->startOfDay();
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', $date)
->whereNotIn('companies.symbol', function ($q) use ($date) => {
$q->select('companies.symbol')
->from('companies')
->leftJoin('articles', 'articles.companies_id', 'companies.id')
->where('articles.created_at', '>', $date)
->distinct()
->get()
})
->orderBy('transaction_date', 'desc')
->distinct()
->get();
It will provide a similar query as you mentioned.
Reference from here.
Also, you can read how to write sub Query from Laravel docs.
Check this one more good answer for that what you need.

Convert mysql query into Eloquent laravel query

I am trying to make the following query in laravel:
SELECT a.name AS subname, a.area_id, b.name, u. id, u.lawyer_id,u.active_search,
FROM subarea a
LEFT JOIN user_subarea u ON u.subarea_id = a.id
AND u.user_id = ?
LEFT JOIN branch b ON a.area_id = b.id
The idea is to obtain the subareas and see if the search is activated by the user.
The user_subarea table might have a record that matches the id of the subarea table where the active_search is equal to 0 or 1. If it doesn't exist I would like the query to return null.
While I was able to achieve this in raw SQL when I try the same with eloquent in Laravel I am not returning any value. I have done the following:
$query = DB::table('subarea')
->join('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Any help will be much appreciated.
I found by myself the answer it was just to add a lefjoin in the first join. It is not in the laravel docs but works too.
$query = DB::table('subarea')
->lefjoin('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Try this one, If you get a problem, please comment.
$value = \Auth::user()->id;
$query = DB::table('subarea')
->where('user_subarea.user_id', '=',$value)
->leftJoin('user_subarea', 'subarea.id', '=', 'user_subarea.subarea_id')
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('subarea.name AS subname','subarea.area_id', 'branch.name', 'user_subarea.id','user_subarea.lawyer_id','user_subarea.active_search')
->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