Search code examples
laraveleloquentlumen

put condition in first array on has many laravel


I had some issues filtering data with my eloquent query builder. I have Transaction Model and Status Model. which transaction has many status. I want to get the first array of hasMany relation and put where. Here is my code.

$var = Transaction::with([
          'status' => function ($q) {
              return $q->first();
           }
       ])->whereHas('status',function ($x){
           return $x->where('status',0);
       })->get();

and the model of a status is

public function status(){
      return $this->hasMany('App\Models\Status','transaction_id','id')->orderBy('status','desc');
}

the result still not give me the right data. it should by returning the data where the first array status value is 0


Solution

  • you can build a new relation using hasOne relation, then load it:

    public function firstStatus(){
          return $this->hasOne('App\Models\Status','transaction_id','id')->orderBy('status','desc')->where('status',0);  // or mybe just ' ->latest() to get the most recent one.
    }
    

    then, you can use this relation like:

    $var = Transaction::with(['firstStatus'])->whereHas('status',function ($x){
               return $x->where('status',0);
           })->get();
    

    this the loaded relation will be the first one.