mardi 19 mars 2019

Laravel 5.7: New Accessor works great but is not recognisable in Repository Class (unknown column) despite of adding $appends to Model

So I have a class Order extends Model.

I created an Accessor called requiresApproval that returns true or false.

public function getRequiresApprovalAttribute(): bool
{
    if ($some_physical_column_from_db === 'does not matter') {
        return true;
    }

    return false;
}

When I have my Order model and I call $order->requiresApproval I get my boolean value. Everything works great.

However I need this accessor to appear on the list of attributes because I want to use it in my repository class in where condition within query.

So based on the official documentation, I added:

protected $appends = [
    'requires_approval',
];

but when I dd() my Order, this attribute is not on the list of attributes (while $appends property indicates the accessor is there).

enter image description here

Long story short:

When in my repository I call:

public function getOrdersEligibleToBeSendToOptions(): Collection
{
    $columns = [
        '*',
    ];

    return $this->model
        ->where('status_uuid', '<>', OrderStatusesInterface::STATUS_COMPLETED)
        ->where('requiresApproval', '=', true) // this fails
        // ->where('requires_approval', '=', true) // this fails as well
        ->get($columns);
}

I get:

enter image description here

What am I doing wrong? How can I use my accessor within repository class?



via Chebli Mohamed

1 commentaire:

  1. OK, this works, but the reason I don't like this solution is the fact that just half of the conditions are on the DB layer, the rest is by filtering what's already fetched.

    If the query is going to return (let's say) thousand of records and filter returns just a few of them I personally see this as a huge waste of DB resource.

    public function getOrdersEligibleToBeSendToOptions(): Collection
    {
    $columns = [
    '*',
    ];

    $results = $this->model
    ->where('status_uuid', '<>', OrderStatusesInterface::STATUS_COMPLETED)
    ->get($columns);

    return $results->filter(function ($value, $key) {
    return $value->requiresApproval === false;
    });
    }

    RépondreSupprimer