Laravel,如何忽略访问器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28015039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel, how to ignore an accessor
提问by Jordi Puigdellívol
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.
但是现在,在一种情况下,我只需要获取一些字段,而没有这个字段OrderContents
。
$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?
但是这样做,它OrderContents
也会返回给我......有没有办法不得到那个字段?
Thanks!
谢谢!
回答by samrap
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
.
令人失望的是,这里的人向您提供了虚假信息。事实上,有一个内置的方法可以实现这一点,直接写入Illuminate\Database\Eloquent\Model
类中,称为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 3087of Illuminate\Database\Eloquent\Model
.
要检索foo
属性,忽略在 中定义的访问器Model::getFooAttribute
,只需调用$myModel->getOriginal('foo');
。这种方法是在线路定义3087的Illuminate\Database\Eloquent\Model
。
Keep in mind that this method gets the originalvalue 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.
请记住,此方法获取模型上的原始值。这意味着如果您对该模型实例上的属性进行任何修改,上述解决方案将不会反映这些修改。只要您只是检索值,就应该没有问题。
回答by Jarek Tkaczyk
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 Messagingon the last step:
或者,您可以在最后一步使用 Laravel 的高阶消息传递:
$openOrders->each->setAppends([]);
回答by lukasgeiter
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:
然后当你想禁用这些$appends
属性时:
Order::$withoutAppends = true;
$openOrders = Order::open()->has('contents')->get(['id','date','tableName']);