0

I have three models

Invoice

Studio

R_studio_pay

Relationships are as follows

studio hasMany Invoice

studio hasOne R_studio_pay

I need to get invoices->where('recurring', 'single')->get() if a column is_r is 1 in R_studio_pay else i don't want the where clause.

I tried using whereHas studio-> wherehas R_studio_pay but conditional where cannot be done.

$invoices = invoice::with('studio')->whereHas('studio', function($query) {
   $query->whereHas('r_studio_pay', function($query) {
       $query->where('is_r', 1);
   });
})->where('recurring', 'single')

But couldn't apply conditional where.

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
sushant
  • 87
  • 7

1 Answers1

0

You are on the right track. However, you should add a return statement in your callbacks. return $query->where('is_r', 1); instead of $query->where('is_r', 1);. Try the code below.

$invoices = invoice::with('studio')->whereHas('studio', function($query){
   return $query->whereHas('r_studio_pay', function($query){
       return $query->where('is_r', 1);
   });
})->where('recurring', 'single');
Odyssee
  • 2,393
  • 2
  • 19
  • 38
  • If is_r = null then i want all invoice. The where clause needs to be conditional on is_r. – sushant Mar 25 '19 at 14:07
  • https://stackoverflow.com/questions/55345529/return-keyword-in-query-callback/55345669?noredirect=1#comment97416867_55345669 – sushant Mar 26 '19 at 05:22