Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel how to return related model data using whereHas

I have Member model Ledger model

class Member extends Model
{
    public function ledger()
    {
        return $this->hasMany('App\Ledger','user_id');
    }
}

I have to get the ledger records of members (need both members and ledger data) where ledger.created_at = a particular date for example ledger.created_at = 2017-03-26 14:15:26

If I run the following script

 $members = Member::whereHas('ledger', function($q){
       $q->where('created_at', '2017-03-26 14:15:26');
 })->get();

I get only members data no ledger records.

If I run the following script

 $members =  Member::with(['ledger' => function($q) {
         $q->where('created_at', '2017-03-26 14:15:26');
     }])->where('type','=','5')->paginate(10);

I get the members with the required ledger records that is good, but it also returns other members where ledger records = null, I do not need the members who do not have a ledger record. (ie I need only members where ledger.created = '2017-03-26 14:15:26 along with the ledger records)

How can I achieve this?

I am using Laravel 5.3

like image 988
Joyal James Avatar asked Mar 10 '23 12:03

Joyal James


1 Answers

Use both whereHas() to filter members and with() to load ledger data:

$members = Member::whereHas('ledger', function($q) {
    $q->where('created_at', '2017-03-26 14:15:26');
})
->with(['ledger' => function($q) {
    $q->where('created_at', '2017-03-26 14:15:26');
}])
->where('type', 5)
->paginate(10);
like image 54
Alexey Mezenin Avatar answered Mar 17 '23 01:03

Alexey Mezenin