Laravel:Eloquent 如果列名包含破折号,如何获取模型的属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20918278/
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: Eloquent How to get property of model if column name contains a dash?
提问by camelCaseD
I have the following in my root route:
我的根路径中有以下内容:
$user = User::all();
return $user->column-one;
Which returns the exception Use of undefined constant one - assumed 'one'even though I do have a column called column-one
from my users table. So how do I get column-one
from my model?
它返回异常Use of undefined constant one - 假设为“one”,即使我确实有一个column-one
从我的用户表中调用的列。那么我如何column-one
从我的模型中获取呢?
回答by camelCaseD
After digging through the source code for the eloquent model I found the magic method __get
and learned that it was just a wrapper for the public function getAttribute
which takes a string thus I'm now able to retrieve the column via $user->getAttribute('column-one');
.
在挖掘了 eloquent 模型的源代码后,我找到了魔法方法,__get
并了解到它只是一个getAttribute
接受字符串的公共函数的包装器,因此我现在可以通过$user->getAttribute('column-one');
.
Edit:
See @Alexandre Butynski's comment below for a better solution than the one I used.
编辑:
请参阅下面@Alexandre Butynski 的评论,以获得比我使用的更好的解决方案。
回答by LF.
I haven't tried this, but am curious if using camelCase for it would work. That's how it works for things like routes. For example: $user->columnOne
.
我还没有尝试过这个,但是很好奇使用camelCase 是否可行。这就是路由之类的工作方式。例如:$user->columnOne
。
I would however recommend renaming that column. That really doesn't map well in a PHP app.
但是,我建议重命名该列。这在 PHP 应用程序中确实不能很好地映射。
Update - Try this:
更新 - 试试这个:
$user->{"column-one"}
$user->{"column-one"}