We have 3 tables transaction, transactionItem and transactionItemStatus all setup with relationships in their respective models, yet when trying to filter transactions by the status of their items the results are unchanged.
Definition of the relationships in the models:
In Transaction.php
public function items()
{
return $this->hasMany('App\Entities\Transaction\TransactionItem\TransactionItem', 'transactionId', 'transactionId');
}
In TransactionItem.php
public function currentStatus()
{
return $this->belongsTo('App\Entities\Transaction\TransactionItem\StatusDefinition', 'currentStatusId', 'statusId');
}
The scope in Transaction.php used to restrict based on the relationship
public function scopeOfTypeDraft($query)
{
$query->whereHas('items.currentStatus', function ($query) {
$query->where('label', '=', 'Draft');
});
}
The use of the scope in a controller
return Transaction::with([
'items',
'items.toTaxYear',
'items.counterpartyId',
'items.currentStatus',
])
->ofTypeDraft()
->get()
As you can see, Transaction
is setup with a hasMany
relationship with TransactionItem
, TransactionItem
is setup with a belongsTo
relationship with Status
. However when we try to restrict the results of an Eloquent query of Transaction
by using a scope (or just a simple ->whereHas()
with a ->where()
) then the results aren't changed compared to omitting the scope. However if we perform a simple the where()
on the collection that is returned, then the results are correctly filtered.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire