laravel how to access column with number name of a table?

后端 未结 12 1266
闹比i
闹比i 2020-12-18 19:11

I make a table with number 22 as the column name. How to access this column?

content:

I\'ve tryed thest

$obj = Tablename::f         


        
相关标签:
12条回答
  • 2020-12-18 19:58

    You can use the following syntax, as found in the variable variables topic in the PHP documentation:

    $obj->{'22'};
    

    ...

    Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

    0 讨论(0)
  • 2020-12-18 19:58

    The question is similar to this:

    Hide number field from Eloquent model in Laravel

    Presently this is not possible in Laravel as seen in this line of code located in vendor\symfony\var-dumper\Symfony\Component\VarDumper\Cloner\VarCloner.php at line 74.

    if ($zval['zval_isref'] = $queue[$i][$k] === $cookie) {
       $zval['zval_hash'] = $v instanceof Stub ? spl_object_hash($v) : null;
    }
    

    Here is the hack.

    if ($zval['zval_isref'] = (isset($queue[$i][$k])) ? ($queue[$i][$k] === $cookie) : false) {
       $zval['zval_hash'] = $v instanceof Stub ? spl_object_hash($v) : null;
    }
    

    Issue has been discussed here:

    https://github.com/laravel/framework/issues/8710

    0 讨论(0)
  • 2020-12-18 19:59

    You can use model attribute $maps to give your troublesome column a different name. Try

    $maps = ['22' => 'twentytwo'];
    
    $hidden = ['22'];
    
    $appends = ['twentytwo'];
    

    Then with your model instance

    echo $model->twentytwo;
    
    0 讨论(0)
  • 2020-12-18 19:59

    Possible duplicate of how can I use exists column with laravel model

    The same answer applies here; you can use $model->getAttribute('22') to get the value of a model attribute.

    0 讨论(0)
  • 2020-12-18 20:03
    $table = Tablename::get();
    
    foreach ($table as $value){
       echo $value->22 // Getting column 22 from table
    }
    
    0 讨论(0)
  • 2020-12-18 20:05

    if you always know the name is 22, you can do this.

     $myfield = 22;
     dd($obj->$myfield);
    

    I tested it and it returns the value in the 22 field correctly.

    0 讨论(0)
提交回复
热议问题