4

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

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

That can be really slow
@peter if you know a faster Eloquent solution, please tell us about it. It's always good to have alternatives to be able to choose the best solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.