lundi 2 avril 2018

Laravel - Filter morphOne or hasOne relationship

I have three models related by a morph relationship.

Shipment can have multiple Status instances, through a StatusHistory class.

    class Status extends Model {
       //id, name
    }

    class Shipment extends Model {
       public function latestStatus() {
          return $this->morphOne('App\StatusHistory', 'model')->latest();
       }
    }

    class StatusHistory extends Model {
       public function model() {
            return $this->morphTo();
        }
    }

I want to get all Shipment entities where the latestStatus has a specific Status name value.

   Shipment::whereHas('latestStatus', function($query) {
      return $query->whereHas('status', function($query) {
         return $query->where('name', 'reserved');
      });
   })->get();

This is not working and returns all entities that have a status of 'reserved', even though the latestStatus can be something else.

Any thoughts?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire