暂时禁用 Laravel 追加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45264901/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:21:56  来源:igfitidea点击:

Temporarily disable Laravel appends

phplaravel

提问by Jenssen

Is it possible to temporarily disable the appendsfunctionality in Laravel 5.4during testing?

是否可以在测试期间暂时禁用该appends功能Laravel 5.4

protected $appends = [
        'full_name',
    ];

I want to ignore that ^.

我想忽略那个^。

I've made a model factory but when I'm testing I don't want to have these append items on my model.

我已经建立了一个模型工厂,但是当我进行测试时,我不想在我的模型上添加这些附加项目。

回答by elegisandi

I have had experience with this too. I've found a good solution here.

我也有过这方面的经验。我在这里找到了一个很好的解决方案。

But, if you like a one-liner solution, you can also use the ff methods of Eloquent's Modelclass:

但是,如果您喜欢单行解决方案,您也可以使用 EloquentModel类的 ff 方法:

  • setHidden(array $hidden)

  • makeHidden(array|string $attributes)

  • setHidden(array $hidden)

  • makeHidden(array|string $attributes)

You can check these here.

您可以在此处查看这些内容。

回答by Ahmed Sayed Sk

I was using this code is suitable: testing for Model name Productfor example

我正在使用此代码是合适的:Product例如测试模型名称

// get product with "id = 1" for example
$needed_product = Product::find(1)->toArray();

// remove un-used attributes
$product = new Product;
foreach ($product->appends as $attr) {
    unset($needed_product[$attr]);
}

Now the $needed_productgets without any appends attributes

现在$needed_product没有任何附加属性

回答by Jenssen

I was thinking something like this:

我在想这样的事情:

/**
 * Get all appended items.
 *
 * @return array
 */
public function getAppends()
{
    $vars = get_class_vars(__CLASS__);

    return $vars['appends'];
}

/**
 * Unset all appended items.
 *
 * @return $this
 */
public function unsetAppends()
{
    collect($this->getAttributes())->pull($this->getAppends());

    return $this;
}

But @elegisandi thanks that works great.

但是@elegisandi 谢谢,效果很好。