Laravel, how to ignore an accessor

2020-02-10 14:03发布

问题:

I have a model with a custom accessor so I get that custom attribute,

    class Order extends GSModel{

        $appends = ['orderContents'];

        public function getOrderContentsAttribute()
        {
            return $this->contents()->get();
        } 
 }

But now, in one case, I need to get only some fields, without this OrderContents one.

$openOrders         = Order::open()->has('contents')->get(['id','date','tableName']);

But doing it this way, it returns me the OrderContents as well.. is there a way to not get that field?

Thanks!

回答1:

There's no way to do it in one go, so here's what you need:

$openOrders = Order::open()->has('contents')->get(['id','date','tableName']);

$openOrders->each(function ($order) {
  $order->setAppends([]);
});

Alternatively, you may use Laravel's Higher Order Messaging on the last step:

$openOrders->each->setAppends([]);


回答2:

Disappointing that people here gave you false information. There is in fact a built in method of achieving this, written straight into the Illuminate\Database\Eloquent\Model class, called Model::getOriginal.

To retrieve the foo attribute, ignoring its accessor defined in Model::getFooAttribute, just call $myModel->getOriginal('foo');. This method is defined on line 3087 of Illuminate\Database\Eloquent\Model.

Keep in mind that this method gets the original value on the model. This means that if you make any modifications to the attribute on that model instance, the above solution will not reflect those modifications. As long as you are just retrieving the value, you should have no problem.



回答3:

Okay I'm not saying this is a good solution, but it works and you get around using a loop...

Add this to your model:

public static $withoutAppends = false;

protected function getArrayableAppends()
{
    if(self::$withoutAppends){
        return [];
    }
    return parent::getArrayableAppends();
}

Then when you want to disable the $appends properties:

Order::$withoutAppends = true;
$openOrders = Order::open()->has('contents')->get(['id','date','tableName']);