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

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

Laravel: Eloquent How to get property of model if column name contains a dash?

phplaraveleloquent

提问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-onefrom my users table. So how do I get column-onefrom 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 __getand learned that it was just a wrapper for the public function getAttributewhich 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"}