skip to Main Content

I have a hasOne relationship. The image shows the records of the relationship which have the same "contract_id"

Following result is required:

I want to only select the last record with the highest "version" => 5, but only if the "status" column is not "draft". Otherwise don’t select the parent record at all if the relationship doesn’t fulfill the condition. ($contract::with(‘latestVersion’)->paginate())

I don’t want to get the next possible record that fullfills the condition – meaning:

I don’t want to get "version 3" with "status active"

enter image description here

I tried to sort by latest() or groupBy(‘version’)…

2

Answers


  1. add ->where('status', '!=', 'draft') to your conditions

    more on the topic: https://laravel.com/docs/10.x/queries#where-clauses

    Login or Signup to reply.
  2. Maybe you can use whereHas or withWhereHas that put additional where conditions on your has queries.

    $contract::whereHas('latestVersion', function ($query) {
        $query->where('version', '=', 5)->where('status', '!=', 'draft');
    })->paginate();
    

    Reference: https://laravel.com/docs/10.x/eloquent-relationships#querying-relationship-existence

    Hope this will be helpful

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