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
Temporary property for Laravel Eloquent model
提问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 (getSecure
and setSecure
methods) to your model.
请注意,最好将其声明为 protected 并将相应的访问器和修改器(getSecure
和setSecure
方法)添加到您的模型中。
回答by mopo922
For those who still find this post (like I did), you may need to explicitly declare the property as null
to prevent it from being automatically added to the attributes
array, and thus being added to INSERT/UPDATE queries:
对于那些仍然找到这篇文章的人(就像我一样),您可能需要明确声明该属性null
以防止它被自动添加到attributes
数组中,从而被添加到 INSERT/UPDATE 查询中:
class User extends Eloquent {
public $secure = null;
// ...
}
资料来源: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 $append
will blow your mind.
如果您打算使用该附加属性,那么$append
您会大吃一惊。
http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/
http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/