skip to Main Content

Last Status Closed Applications

User
table 1: applications

id(pk) name
1 naveed

table 2: statuses

id(pk) status application_id(fk)
1 pending 1
2 submitted 1
3 closed 1
4 observation 1

now i want to get list of applications if last status is closed.
only add this application in list which last status is closed.
note: this application not added into list which have at least one status closed.

The given blow code is wrong.

$applicationsWithClosedStatus = Application::whereHas('statuses', function ($query) {
    $query->where('status', 'closed');
})->get();

another wrong

public function status() {
        return $this->hasOne(Status::class)->latest ();
    }
$applicationsWithLastClosedStatus = Application::whereHas('status', function ($query) {
    $query->where('status', 'closed');
})->get();

3

Answers


  1. try this

    DB::select("select id from applications where id in (select application_id from (select max(id), application_id from statuses where status="closed" group by application_id) AS t1)")
    
    Login or Signup to reply.
  2. gets data if the last status is closed

    SELECT s.*
    FROM statuses as s
    INNER JOIN applications as a on a.id = s.application_id
    WHERE s.id IN (  
      SELECT MAX(s.id) as max_id
      FROM statuses as s 
      GROUP BY s.application_id
    ) AND s.status = 'closed'
    
    
    Login or Signup to reply.
  3. I usually solve it as follows:
    In the model like a ApplicationModel that extends the IlluminateDatabaseEloquentModel have a function like yours as status.
    But like this

    use IlluminateDatabaseEloquentRelationsHasMany;
    use IlluminateDatabaseEloquentModel;
    use ......Status;
    
    ....
    
    public function status(): HasMany
    {
        return $this->hasMany(Status::class);
    }
    

    Now you can use like so:

    use ......Application;
    
    ...
    
    public function getApplicationWithStatus()
    {
        $application = new Application();
        $result = $application::with('status')
          ->where('status', 'closed')
          ->get();
    
        return $result !== null ? $result : false;
    }
    

    Now in the result should be the expected result.
    Hope it helped.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search