Laravel Eloquent 模型的临时属性

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

Temporary property for Laravel Eloquent model

phplaraveleloquent

提问by Nick

I have a Laravel Eloquent model User, which has a table with username and email columns. I need to add a property for the model on runtime, something like $user->secure. This property doesn't need to go to database.

我有一个 Laravel Eloquent 模型用户,它有一个包含用户名和电子邮件列的表。我需要在运行时为模型添加一个属性,例如 $user->secure。这个属性不需要去数据库。

When i add this property and hit $user->save() i get an error saying i don't have database column 'secure'. I can unset 'secure' before save but somehow it feels there should be a better way to do so. Any suggestions?

当我添加此属性并点击 $user->save() 时,我收到一条错误消息,提示我没有数据库列“安全”。我可以在保存之前取消设置“安全”,但不知何故,感觉应该有更好的方法来做到这一点。有什么建议?

回答by Thomas Ruiz

Just add an attribute to your class.

只需为您的类添加一个属性即可。

class User extends Eloquent {
  public $secure;

  // ...
}

Note that it is better to declare it protected and add corresponding accessors and mutators (getSecureand setSecuremethods) to your model.

请注意,最好将其声明为 protected 并将相应的访问器和修改器(getSecuresetSecure方法)添加到您的模型中。

回答by mopo922

For those who still find this post (like I did), you may need to explicitly declare the property as nullto prevent it from being automatically added to the attributesarray, and thus being added to INSERT/UPDATE queries:

对于那些仍然找到这篇文章的人(就像我一样),您可能需要明确声明该属性null以防止它被自动添加到attributes数组中,从而被添加到 INSERT/UPDATE 查询中:

class User extends Eloquent {
    public $secure = null;

    // ...
}

Source: http://laravel.io/forum/02-10-2014-setting-transient-properties-on-eloquent-models-without-saving-to-database

资料来源:http: //laravel.io/forum/02-10-2014-setting-transient-properties-on-eloquent-models-without-saving-to-database

回答by mangonights

If you intend to make use of that add-on property, then $appendwill blow your mind.

如果您打算使用该附加属性,那么$append您会大吃一惊。

http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/

http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/