英文:
Laravel Eloquent unable to read data from databse table columns with numerical column names
问题
I have a mysql table used for a Laravel model. The table contains some columns whose names are purely numeric, i.e. contain only numbers which are years. Please see image attached below.
When I query the table using eloquent the result results returned are missing the numerical column names. Even though the values are returned, the column names are deformed and display as single digit numbers.
When using accessors, I'm able to return the columns with friendly names however I am not able to update the model columns.
So my questions are
- What is the best way to read and update the columns?
- I'm not able to change the column names so the only option is to find a work around in my laravel code.
英文:
I have a mysql table used for a Laravel model. The table contains some columns whose names are purely numeric, i.e. contain only numbers which are years. Please see image attached below.
When I query the table using eloquent the result results returned are missing the numerical column names. Even though the values are returned, the column names are deformed and display as single digit numbers.
When using accessors, I'm able to return the columns with friendly names however I am not able to update the model columns.
So my questions are
- What is the best way to read and update the columns?
- I'm not able to change the column names so the only option is to find a work around in my laravel code.
答案1
得分: 2
I guess this is because you can't name PHP variables with names starting with a number.
So to update the value, you will need to write setters in addition to your getters. You should be able to do that with Eloquent accessors and mutators.
Edit: After some tests, I didn't find how to do it with accessors and mutators, but I came up with another solution that might work, given Tim Lewis's comment.
public function setYear($yearColumnName, $value)
{
$this->{$yearColumnName} = $value;
}
英文:
I guess this is because you can't name php variables with names starting with a number.
So to update the value you will need to write setters in addition to your getters. You should be able to do that with Eloquent accessors and mutators.
https://laravel.com/docs/10.x/eloquent-mutators#defining-a-mutator
Edit: After some test, I didn't find how to do it with accessors and mutators, but I came up with another solution who might be working given Tim Lewis's comment.
public function setYear($yearColumnName, $value)
{
$this->{$yearColumnName} = $value;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论