Mysql Raw Count Only - php

I use to PHP and Laravel Framework on my project.
Above code works perfectly
$users = User::select([
'users.id',
'users.name',
'users.company',
'users.country',
'users.city',
'users.email',
'users.created_at',
\DB::raw('SUM(reservations.dolar) as dolar'),
\DB::raw('count(reservations.confirmation) as confirmation'),
])->join('reservations','reservations.user_id','=','users.id')
->groupBy('reservations.user_id');
Now Counting all reservation.confirmation column but I want to count only reservation.confirmation column values 1
How I can edit
\DB::raw('count(reservations.confirmation) as confirmation'),
this code

Have you tried see in https://laravel.com/docs/5.6/queries#joins in the section "Advanced Join Clauses", you can add condition in Join function
$users = User::select([
'users.id',
'users.name',
'users.company',
'users.country',
'users.city',
'users.email',
'users.created_at',
\DB::raw('SUM(reservations.dolar) as dolar'),
\DB::raw('count(reservations.confirmation) as confirmation'),
])->join('reservations', function ($join) {
$join->on('reservations.user_id', '=', 'users.id')
->where('reservations.confirmation', '=', 1);
})->groupBy('reservations.user_id');

If you want have all sum dolar not depends with confirmation,
you can use 'case' statement:
\DB::raw('sum(case when reservations.confirmation=1 then 1 else 0 end) as confirmation')
or subquery:
\DB::raw('(Select count(*) FROM reservations WHERE user_id = users.id AND confirmation=1) as confirmation')

Related

Laravel WHERE scope on JOIN

I am trying to get "shifts" and get all records I have,
But I join it with orders and run where on orders by delivery_date here "the shift" which has no orders erased
now I need to make the where only on orders and not affect on shifts
Shift::leftJoin('mt_plans', 'mt_plans.shift_id', '=', 'shifts.id')
->leftJoin('subscriptions', 'subscriptions.plan_id', '=', 'mt_plans.plan_id')
->join('orders', 'orders.subscription_id', '=', 'subscriptions.id')
->join('mt_order_details', 'mt_order_details.order_id', '=', 'orders.id')
->join('mt_item', 'mt_item.item_id', '=', 'mt_order_details.item_id')
->where('orders.delivery_date', $request->date)
->whereIn('orders.status', [OrderStatus::ACCEPTED, OrderStatus::ASSIGNED, OrderStatus::FAILED, OrderStatus::SUCCESSFUL])
->select([
'mt_item.item_id as meal_id',
'mt_item.en_name',
'mt_item.color',
'mt_item.label_number',
'shifts.id as shift_id',
'shifts.title',
'shifts.start_time',
'shifts.end_time',
'shifts.pickup_time'
])
->get();
You need a left join where your condition applies:
Shift::leftJoin('mt_plans', 'mt_plans.shift_id', '=', 'shifts.id')
->leftJoin('subscriptions', 'subscriptions.plan_id', '=', 'mt_plans.plan_id')
->leftJoin('orders', function($q) use($request) {
$q->on('orders.subscription_id', '=', 'subscriptions.id');
$q->where('orders.delivery_date', '=', $request->date);
})
->leftJoin('mt_order_details', 'mt_order_details.order_id', '=', 'orders.id')
->leftJoin('mt_item', 'mt_item.item_id', '=', 'mt_order_details.item_id')
->whereIn('orders.status', [OrderStatus::ACCEPTED, OrderStatus::ASSIGNED, OrderStatus::FAILED, OrderStatus::SUCCESSFUL])
->select([
'mt_item.item_id as meal_id',
'mt_item.en_name',
'mt_item.color',
'mt_item.label_number',
'shifts.id as shift_id',
'shifts.title',
'shifts.start_time',
'shifts.end_time',
'shifts.pickup_time'
])
->get();
Then you keep all "shifts" but join only order with delivery_date condition.
Keep in mind that it will retrieve all "shifts" where where condition applies. The orders will be null if doesn't match the id and delivery_date

Laravel 5.4 query builder having issues with groupBy

I'm trying to convert this query to query builder in Laravel 5.4:
SELECT
oc.id,
oc.name,
oat.user_id,
p.first_name,
p.last_name
FROM
oauth_clients oc
LEFT JOIN oauth_access_tokens oat ON oc.id = oat.client_id
JOIN users u on u.id = oat.user_id
JOIN people p on p.id = u.person_id
WHERE oc.revoked = false AND oc.password_client = true
GROUP BY oc.id, oat.user_id
And getting this error barf: Argument 1 passed to Illuminate\Database\Connection::prepareBindings() must be of the type array, string given, called in /var/www/html/source/luniverse/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 648 and defined
This is my attempt at it (one of many):
$tokens = DB::select('oc.id','oc.name','oat.user_id','p.first_name','p.last_name')
->from('oauth_clients as oc')
->leftJoin('oauth_access_tokens as oat', 'oc.id', '=', 'oat.client_id')
->join('users as u', 'u.id', '=', 'oat.user_id')
->join('people as p', 'p.id', '=', 'u.person_id')
->where('oc.revoked', '=', 'false')
->where('oc.password_client', '=', 'true')
->groupBy('oc.id')
->groupBy('oat.user_id')
->get();
The database config is set to strict mode, but that doesn't exactly seem to explain that particular error. The raw query runs fine in a DB gui.
Change the groupby code like
$tokens = DB::select('oc.id','oc.name','oat.user_id','p.first_name','p.last_name')
->from('oauth_clients as oc')
->leftJoin('oauth_access_tokens as oat', 'oc.id', '=', 'oat.client_id')
->join('users as u', 'u.id', '=', 'oat.user_id')
->join('people as p', 'p.id', '=', 'u.person_id')
->where('oc.revoked', '=', 'false')
->where('oc.password_client', '=', 'true')
->groupBy('oc.id','oat.user_id')
->get();
DB::select() executes a query, you have to use DB::table():
DB::table('oauth_clients as oc')
->select('oc.id','oc.name','oat.user_id','p.first_name','p.last_name')

Laravel Eloquent Complex Join Statement - specific example provided

I have the following raw SQL that I'm trying to convert into Eloquent form:
SELECT oe.eventID, oe.eventName, oet.etName, date_format(oe.eventStartDate, '%c/%d/%Y') as eventStartDate,
date_format(oe.eventEndDate, '%c/%d/%Y') AS eventEndDate
FROM `org-event` oe
JOIN `org-event_types` oet on oe.eventTypeID=oet.etID and oet.orgID=?
JOIN `event-registration` er on er.eventID = oe.eventID
WHERE (er.regStatus='Active' or er.regStatus='In Progress') AND personID=? AND oe.deleted_at is NULL
ORDER BY oe.eventStartDate DESC
I've crafted the following and I'm running into an error saying that '10' isn't a column. 10 is the value of $this->currentPerson->defaultOrgID
DB::table('org-event')
->join('org-event_types', function($join) {
$join->on('org-event_types.etID', '=', 'org-event.eventTypeID');
$join->on('org-event_types.orgID', '=', $this->currentPerson->defaultOrgID);
})->join('event-registration', 'event-registration.eventID', '=', 'org-event.eventID')
->where('event-registration.personID', '=', auth()->user()->id)
->where(function($w) {
$w->where('event-registration.regStatus', '=', 'Active')
->orWhere('event-registration.regStatus', '=', 'In Progress');
})
->select('org-event.eventID', 'eventName', 'etName', 'eventStartDate', 'eventEndDate')
->orderBy('org-event.eventStartDate')->get();
I dropped the deleted_at where clause because that's automatic using eloquent.
You have to join on the corresponding foreign key: oe.eventTypeID=oet.etID and then supply a where explaining what you want to filter your results by, i.e. ->where('orgID','=',$this->currentPerson->defaultOrgID).
DB::table('org-event')
->join('org-event_types', function($join) {
$join->on('org-event_types.etID', '=', 'org-event.eventTypeID');
$join->on('org-event_types.orgID', '=', 'org-event.eventTypeID')->where('orgID','=',$this->currentPerson->defaultOrgID);
})->join('event-registration', 'event-registration.eventID', '=', 'org-event.eventID')
->where('event-registration.personID', '=', auth()->user()->id)
->where(function($w) {
$w->where('event-registration.regStatus', '=', 'Active')
->orWhere('event-registration.regStatus', '=', 'In Progress');
})
->select('org-event.eventID', 'eventName', 'etName', 'eventStartDate', 'eventEndDate')
->orderBy('org-event.eventStartDate')->get();

relationship of 3 tables in laravel

Given that I have 3 tables: user, competences and competences_user, how can I get the list of skills of each user with query-builder?
Table structures:
user: id, nom....
competences: id, titre...
competences_user : id, competence_id, user_id...
Here is what I have tried so far:
select user.id, user.nom, competences.titre
FROM user
Inner Join competences_user
ON = competences_user.competence_id AND user.id = competence_user.user_id
Inner Join competences
ON competences.id = competence_user.competence_id
There is many ways to do it , the easy way without the query builder :
ie :
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
To answer your question :
$users = DB::table('users')
->join('competences_user', 'competences_user.user_id', '=', 'users.id')
->join('competences', 'competences_user.competence_id', '=', 'competences.id')
->select('users.*', 'competences.titre')
->get();
You can refer to the documentation for more details.

DISTINCT method using Laravel 5 eloquent query builder

I'm struggling to get unique results when using the DISTINCT method in laravel. This is my query
//Get users that are part of this sector
$users = DB::table('users')->distinct()
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->get();
dd($users);
The result shows 3 users with the same ID, when I only want one of them in the results.
How should I change my query?
Try to use group by id
$users = DB::table('users')
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->groupBy('users.id')
->get();
dd($users);

Categories