Laravel:Eloquent如果列名包含破折号,如何获取模型的属性? [英] Laravel: Eloquent How to get property of model if column name contains a dash?

查看:96
本文介绍了Laravel:Eloquent如果列名包含破折号,如何获取模型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的根路径如下:

  $ user = User :: all(); 
return $ user-> column-one;

其中返回异常 使用未定义的常量一 - 假设'一' / em> ,即使我的用户表中有一个名为 column-one 的列。那么如何从我的模型中获得 column-one

解决方案

在挖掘雄辩模型的源代码之后,我发现了魔术方法 __ get ,并了解到它只是公共函数的包装器 getAttribute 它需要一个字符串,因此我现在可以通过 $ user-> getAttribute('column-one'); 。 p>

编辑:

请参阅@Alexandre Butynski的评论,以获得比我所使用的更好的解决方案。


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?

解决方案

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');.

Edit:
See @Alexandre Butynski's comment below for a better solution than the one I used.

这篇关于Laravel:Eloquent如果列名包含破折号,如何获取模型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆