Laravel eloquent where current status is equals to string - mysql

I have a candidate and a status table which every candidate have multiple statuses. when statuses changes new row in statuses table will be created to store new status. So when user wants to filter candidates by status I want to select candidates that their current status is what user select not the all before statuses.
my query is :
$status = $request->get('status');
$q->where(function ($q) use ($status) {
$q->orWhereHas('statuses', function ($q) use ($status) {
$q->where('status', 'like', "%" . $status . "%");
});
});

I changed the query to the blow and it's working fine.
$q->whereRaw('status LIKE "%'.$status.'%" AND id=(select max(id) from statuses WHERE status LIKE "%'.$status.'%")');
EDIT:
The query in above has a problem and that is it's only get's first matching candidate not all of them so I changed the query to this:
$q->where(function ($q) use ($status) {
$q->orWhereHas('statuses', function ($q) use ($status) {
$q->whereRaw('status LIKE ? AND id IN (SELECT MAX(id) FROM statuses GROUP BY candidate_id)',["%".$status."%"]);
});
});

my percipience is, current status of a candidate is last record.
i say mysql direction, as for your migrate and modeling, implement this.
select * from status
where id =(
select max(id) from status
where candidate_id= x
)
x is candidate id.

Related

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

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.

Count number of entries made by id in a table in Yii2?

I have a table like this now what i want to do is count the records for each ID where STATUS is COMPLETED
.
Something like SELECT COUNT(*) FROM TABLE WHERE ID= foreach(ID)
AND STATUS=1
select id, count(id) as count from table where status='COMPLETED' group by id;
Basically you need to use group by clause in MySQL.
You can do it using Active Record as this:
I assuming you have you table model named like Job, then you can get a needed value as this:
$number = Job::find()->where(['STATUS' => 'Completed'])->count();
or it is always better to store constant properties in the model like this:
class Job extends ActiveRecord {
const STATUS_COMPLETED = 'Completed';
then your ActiveQuery will look like this:
$number = Job::find()->where(['STATUS' => Job::STATUS_COMPLETED])->count();
Also here is the full description: Querying Data
$any_var = Your_Table::find()->where(['status' => 'Cimpleted'])->select('id')->orderBy('id')->groupBy('id')->count ();

How to get last record of duplicate data?

I have table A ( id - message - user_id ), I need to say if any user_id duplicated in table just bring last one that user had added:
My controller code (my wrong shut):
$duplicate = VerfiyRequest::where('user_id', '>' , 1)->first();
$VerfiyRequests = VerfiyRequest::latest()->get();
return view('backend.VerfiyRequest.index' , compact('VerfiyRequests'));
Use this to get the last record of each user by the latest id (incrementing primary key):
VerfiyRequest::whereIn('id', function ($query) {
$query
->from('verify_requests')
->select(DB::raw('MAX(id) as id'))
->groupBy('user_id');
})->get();
Explanation: the MAX(id) as id selects latest id of each user group, so the inner query returns latest record of each user.

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

Trouble counting rows with specific value - Doctrine, Symfony2, mysql

I'm working on querying my mysql database via doctrine in a symfony2 app. I have a basic table set up that includes an id number ('id'), name ('name'), and a last column for if the person has been contacted ('contacted'), depicted with 0 or 1. I can query and get the number of total inquiries (depicted in the controller with $inquiryCountTotal just fine.
I'm struggling to count the rows that have been contacted. I figure I can either COUNT the rows with a value of 1 in the contacted column or I could just SUM all the rows in the contacted column.
For some reason it seems to be summing the ids, as I have 8 ids and it's spitting a number of 36.
Where am I going wrong? Thanks in advance!
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EABundle:Inquiry')
->findBy(array(), array('id'=>'DESC'));
$inquiryCountTotal = $em->createQuery("
SELECT count(id)
FROM EABundle:Inquiry id
")->getSingleScalarResult();
//This is the part I'm struggling with...
$inquiryCount = $em->createQuery("
SELECT sum(contacted)
FROM EABundle:Inquiry contacted
")->getSingleScalarResult();
return $this->render('EABundle:Inquiry:index.html.twig', array(
'entities' => $entities,
'inquiryCount' => $inquiryCount,
'inquiryCountTotal' => $inquiryCountTotal
));
}
Doctrine is interpreting the alias as the id of the entity.
Try this:
$inquiryCount = $em->createQuery("
SELECT sum(i.contacted)
FROM EABundle:Inquiry i
")->getSingleScalarResult();