Laravel,如何忽略访问者 [英] Laravel, how to ignore an accessor

查看:600
本文介绍了Laravel,如何忽略访问者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自定义访问器的模型,所以我得到这个自定义属性,

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']);

但是这样做,它返回我的 OrderContents 还有..
有没有办法得到该字段?

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

谢谢!

推荐答案

好的,我不是说这是一个很好的解决方案,但它可以使用循环来实现...

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();
}

然后,当您要禁用 $ appends 属性:

Then when you want to disable the $appends properties:

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

这篇关于Laravel,如何忽略访问者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆