Laravel:如果列名包含破折号,如何获得模型的属性?

时间:2022-10-16 08:25:25

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?

它返回未定义常量1的异常使用——假设为“1”,尽管我确实有一个列,名为columone,来自我的users表。那么如何从模型中得到第一列呢?

2 个解决方案

#1


15  

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

在深入研究了有说服力的模型的源代码之后,我发现了神奇的方法__get,并了解到它只是一个公共函数getAttribute的包装器,它接受一个字符串,因此我现在可以通过$user->getAttribute('column- 1 ')检索列;

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

编辑:见下面@Alexandre Butynski的评论,找到比我使用的更好的解决方案。

#2


2  

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是否有用。这就是它的工作原理。例如:用户- > 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 - > { "列1 " }

#1


15  

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

在深入研究了有说服力的模型的源代码之后,我发现了神奇的方法__get,并了解到它只是一个公共函数getAttribute的包装器,它接受一个字符串,因此我现在可以通过$user->getAttribute('column- 1 ')检索列;

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

编辑:见下面@Alexandre Butynski的评论,找到比我使用的更好的解决方案。

#2


2  

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是否有用。这就是它的工作原理。例如:用户- > 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 - > { "列1 " }