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

跟風遠走 提交于 2020-01-01 03:12:09

问题


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:


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.




回答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.

I would however recommend renaming that column. That really doesn't map well in a PHP app.

Update - Try this:

$user->{"column-one"}



来源:https://stackoverflow.com/questions/20918278/laravel-eloquent-how-to-get-property-of-model-if-column-name-contains-a-dash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!