Couldn't use the whereNotExists clause correctly in Laravel 8 Eloquent - mysql

I have 2 tables, one with different users, and the second table is an invoice table called "factures" and has a foreign key of userid, I called it client_id, which I am trying to get is the number of clients created_by a certain administrator and who have no invoices yet, here is what I tried:
$clients = User::select('id')
->where([['created_by',$membre_id],['role','Client']])
->orWhere([['updated_by',$membre_id],['role','Client']])
->whereNotExists(function($query)
{
$query->select(DB::raw('client_id'))
->from('factures')
->where('created_by',$member_id);
})->get();
but this query gives me all clients created_by $member_id without exception.
What is wrong with my query?

Did you try the following:
$clients = User::select('id')
->where(function($query) use($member_id){
$query->where([['created_by',$membre_id],['role','Client']])
->orWhere([['updated_by',$membre_id],['role','Client']])
})
->whereNotExists(function($query) use($member_id){
$query->select(DB::raw('client_id'))
->from('factures')
->where('created_by',$member_id);
})
->get();
}
This answer applied the OR condition only between the first two conditions (created_by and updated_by) and its result is AND with the third condition.

Related

hasMany on Cakephp 4

I want to make a transaction with 1 transaction many products. but I have a problem only the last index entered on the product. is there a solution?this is my controller
[Model Table][2]
just make sure you are using an array on select query. to fetch all the records.
For eg,
$posts = $this->Employees->find("all")
->contain(["employeePosts" => function($q){
return $q->select(["id", "employee_id", "post_title"]);
}])
->toList();
echo print_r("posts");
here employee_id is a foreign key. and employeePosts is a key I created in EmployeesTable in hasMany()
$this->hasMany("employeeposts")->setClassName("Posts")

groupBy is expecting more table columns in many to many relationship

I'm trying to get all the roles permission which has a many to many relationship. I want to get all the permissions of a single role. Here I'm trying to use groupBy but it gives me error.
$search_role = DB::table('roles')
->join('roles_permissions','roles_permissions.role_id','roles.id')
->join('permissions','permissions.id','roles_permissions.permission_id')
->where('roles.name', 'like', "%$request->searcher%")
->orWhere('permissions.name', 'like', "%$request->searcher%")
->select('roles.name as role_name', 'permissions.name as permission_name','roles_permissions.*')
->groupBy('roles_permissions.role_id')
->get();
Error here:
roles_permissions.permission_id isn't in groupBy.
If I add that I get another column isn't in groupBy.
you don't have any aggregation operation in select statement. check my example
$search_role = DB::table('roles')
->join('roles_permissions','roles_permissions.role_id','roles.id')
->join('permissions','permissions.id','roles_permissions.permission_id')
->where('roles.name', 'like', "%$request->searcher%")
->orWhere('permissions.name', 'like', "%$request->searcher%")
->select('role_id', DB::raw('count(*) as total')) //example
->groupBy('roles_permissions.role_id')
->get();
what you are trying to do does not makes sense. Group by does not work in that way.
SELECT role_id, count(*)
from roles
group by role_id
is valid
SELECT roles.*, count(*)
from roles
group by role_id
is not. in the latter case, you generally need to add every column which is not aggregated to group by statement

Laravel multiple where clause

I was trying to get list of foods which are in cart as well as favorites table.
I used the following Query to access it. In Conditional Clauses section i wanted to check if the food is in favorites table it also shows or if it's in carts table also will be shown. But it can't check inside the where clause means the foods id is in the carts table but not in that user. So it should return cart_id as null but it shows cart_id though that user didn't add into his carts table. Same happened in favorites table. How can i make it correct?
$foods = DB::table('foods')
->leftjoin('carts','carts.food_id','foods.id')
->leftjoin('favorites','favorites.food_id','foods.id')
->select('foods.food_name', DB::raw('carts.id as cart_id'),DB::raw('favorites.id as favorite_id'),'foods.id','foods.display_image','foods.price','foods.category_id','foods.description','foods.restaurant_id' )
->where('foods.restaurant_id','=',$request->Input(['restaurant_id']))
->orwhere(function ($query) {
$query->where('carts.user_id','=',Auth::user()->id)
->where('favorites.user_id','=',Auth::user()->id);
})
->get();
Assume you are querying foods that belong to a restaurant AND user who added to cart OR liked it, you conditional clause in SQL is:
WHERE restaurant_id=:restaurant_id
AND (carts.user_id=:user_id OR favorites.user_id=:user_id)
Your laravel conditional clause will then be:
->where('foods.restaurant_id', $request->input('restaurant_id')
->where(function ($query) {
$query->where('carts.user_id', Auth::user()->id)
->orWhere('favorites.user_id', Auth::user()->id);
})
Try this:
$foods = DB::table('foods')
->leftJoin('carts', function($join) {
$join->on('carts.food_id', 'foods.id')
->where('carts.user_id', Auth::id());
})
->leftJoin('favorites', function($join) {
$join->on('favorites.food_id', 'foods.id')
->where('favorites.user_id', Auth::id());
})
->select(...)
->where('foods.restaurant_id', $request->input('restaurant_id'))
->get();
BTW: You don't need DB::raw() for column aliases:
->select('carts.id as cart_id')

How to fetch records from two different tables in laravel5.2

I have two tables 'approval' and 'renewal', both having a common column 'applicant_id'.
When new application comes-in, it stores a data-record in table 'approval' alongwith the 'applicant_id' for whom the record has been added.
Now, when there is a renew applied for that same applicant, the row gets created in the table 'renewal' referencing the 'applicant_id'
Note: There can be a single record in the table 'approval' for a 'applicant_id' but there can be more than one record for the same 'applicant_id' in the table 'renewal'.
Now, my requirement is:
I need to fetch the records from both the table for all the applicants.
Conditions: If there is a data for the 'applicant_id' in both the table and 'renewal' table has multiple row for the same 'applicant_id', then I need to get the records from 'renewal' table only that too the latest one.
If there is no data in 'renewal' table but exists in 'approval' table for the 'applicant_id', then the fetch record should get the data present in 'approval' table.
Basically, if there is record for the applicant in 'renewal' table, get the latest one from there, if there is record present only in 'approval' table, then get that one but the preference should be to get from 'renewal' if exists.
I am trying to do this in laravel 5.2. So, is there anyone who can help me in this?
If you're using Eloquent, you'll have 2 models:
Renewal.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Renewal extends Model
{
protected $table = 'renewal';
public static function findMostRecentByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->orderBy('date_created', 'desc')
->first();
return $applicant;
}
}
Approval.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Approval extends Model
{
protected $table = 'approval';
public static function findByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->first();
return $applicant;
}
}
Then, in the code where you want to get the approval/renewal record, use the following code:
if (! $record = Renewal::findMostRecentByApplicantId($applicantId)) {
$record = Approval::findByApplicantId($applicantId);
}
//$record will now either contain a valid record (approval or renewal)
//or will be NULL if no record exists for the specified $applicantId
After few try, I got one way to do it using raw:
SELECT applicant_id, applicant_name, applicant_email, applicant_phone, renewed, updated_at
FROM (
SELECT renewal_informations.applicant_id, renewal_informations.applicant_name, renewal_informations.applicant_email, renewal_informations.applicant_phone, renewal_informations.renewed, renewal_informations.updated_at
FROM renewal_informations
UNION ALL
SELECT approval_informations.applicant_id, approval_informations.applicant_name, approval_informations.applicant_email, approval_informations.applicant_phone, approval_informations.renewed, approval_informations.updated_at
FROM approval_informations
) result
GROUP BY applicant_id
ORDER BY applicant_id ASC, updated_at DESC;
For every single Approval id, there can b multiple records for renewal table suggests you have One to Many relation. which you can define in the your Model like
Approval.php (App\Models\Approval)
public function renewal()
{
return $this->hasMany('App\Models\Renewal', 'applicant_id')
}
Having defined this relation. you can get the records from the table using applicant_id.
$renewal_request_records = Approval::find($applicant_id)->renewal();
This will get all records from renewal table against that applicant_id.
Finding the latest
$latest = Renewal::orderBy('desc', 'renewal_id')->first();
Further Readings Eloquent Relations

How can I select with count() on specific user in Laravel?

Here is my Database structure:
Also - there is a table users and reciever_id references that table id.
I use that query to get count of each type of notifications as well as data for that type of notifications from notification_types table.
Notification::
select('notification_types.*', DB::raw('count(*) as total'))
->join('notification_types', 'notifications.type_id', '=', 'notification_types.id')
->groupBy('notifications.type_id')
->get()
What I need - is to set constraint on reciever_id, I just don't get - where should I put the where clause?
Just chain the where method anywhere before get, since your condition will be applied on the notifications table:
Notification::select('notification_types.*', DB::raw('count(*) as total'))
->join('notification_types', 'notifications.type_id', '=', 'notification_types.id')
->where('reciever_id', $receiverId)
->groupBy('type_id')
->get();
Also, there's no need with this query to group by notifications.type_id, type_id will do, because there are no ambiguities created here because there are no other columns named type_id.