I have a model called Transfer
and a model called Account
, and two relations in my Transfer
model:
public function outgoing()
{
return $this->belongsTo(Account::class, 'outgoing_id');
}
public function incoming()
{
return $this->belongsTo(Account::class, 'incoming_id');
}
This is used to transfer money from my bank account to my wallet for example, or from my credit card to my bank, and so on..
So an account can have a few types. For instance, bank
can be an account type. Now if I want to grab all outgoing bank related transfers, by using the actual name bank
, I have to use an additional relation, for example:
public function outgoingbank()
{
return $this->belongsTo(Account::class, 'outgoing_id')->where('type', 'bank');
}
And to grab all outgoing transfers that are bank
transfers, I can now use this:
auth()->user()->transfers()->has('outgoingbank')->get();
But my question is, is there a better way to do this with for example query scopes in my Account
model, instead of adding an additional relation for each account type
? Or perhaps an accessor in my Transfer
model?
Fixed it using whereHas, which just popped into my brain all of a sudden:
$bank_transfers = auth()->user()->transfers()->with('outgoing')->whereHas('outgoing', function ($query){
return $query->where('type', 'bank');
})->get();