laravel如何访问具有表的数字名称的列?

时间:2017-01-18 04:41:06

标签: php arrays database laravel object

我创建一个数字为22的表作为列名。如何访问此专栏?

enter image description here

含量:

enter image description here

我试过了

$obj = Tablename::find(1)->first();
$obj->22;
$obj->'22';   //'syntax error, unexpected ''22''
$obj->"22";
$obj->`22`;
$obj[22];
$arr = $obj->toArray();
var_dump($arr); //  array(15) { ["id"]=> string(2) "25" ["out_trade_no"]=> string(14) "14847080930025" ["22"]=> string(0) "2"
$arr[22];       // 'ErrorException' with message 'Undefined offset: 22'
$arr['22'];     // 'ErrorException' with message 'Undefined offset: 22'
$arr["22"];     // 'ErrorException' with message 'Undefined offset: 22'
$arr[`22`];     // 'ErrorException' with message 'Undefined index: ' in
$arr[{'22'}];   //  'syntax error, unexpected '{', expecting ']'' in

无效。

编辑为实现的答案:也得到null。

var_dump($orders[0]);
var_dump($orders[0]->id);
var_dump($orders[0]->{'22'});
$col = '22';
$res = $orders[0]->{$col};
var_dump($res);

输出:

object(Order)#537(21){
    [
        "connection": protected
    ]=>NULL[
        "table": protected
    ]=>NULL[
        "primaryKey": protected
    ]=>string(2)"id"[
        "perPage": protected
    ]=>int(15)[
        "incrementing"
    ]=>bool(true)[
        "timestamps"
    ]=>bool(true)[
        "attributes": protected
    ]=>array(15){
        [
            "id"
        ]=>string(2)"25"[
            "out_trade_no"
        ]=>string(14)"14847080930025"[
            "22"
        ]=>string(1)"2"[
            "user_id"
        ]=>string(2)"49"[
            "product_name"
        ]=>string(4)"test"[
            "amount"
        ]=>string(1)"3"[
            "fee"
        ]=>string(4)"0.03"[
            "address_id"
        ]=>string(1)"3"[
            "trade_status"
        ]=>string(13)"TRADE_SUCCESS"[
            "express_name"
        ]=>string(0)""[
            "express_no"
        ]=>string(0)""[
            "buyer_email"
        ]=>string(0)""[
            "modify_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "created_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "updated_at"
        ]=>string(19)"2017-01-18 10:55:26"
    }[
        "original": protected
    ]=>array(15){
        [
            "id"
        ]=>string(2)"25"[
            "out_trade_no"
        ]=>string(14)"14847080930025"[
            "22"
        ]=>string(1)"2"[
            "user_id"
        ]=>string(2)"49"[
            "product_name"
        ]=>string(4)"test"[
            "amount"
        ]=>string(1)"3"[
            "fee"
        ]=>string(4)"0.03"[
            "address_id"
        ]=>string(1)"3"[
            "trade_status"
        ]=>string(13)"TRADE_SUCCESS"[
            "express_name"
        ]=>string(0)""[
            "express_no"
        ]=>string(0)""[
            "buyer_email"
        ]=>string(0)""[
            "modify_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "created_at"
        ]=>string(19)"2017-01-18 10:54:53"[
            "updated_at"
        ]=>string(19)"2017-01-18 10:55:26"
    }[
        "relations": protected
    ]=>array(0){

    }[
        "hidden": protected
    ]=>array(0){

    }[
        "visible": protected
    ]=>array(0){

    }[
        "appends": protected
    ]=>array(0){

    }[
        "fillable": protected
    ]=>array(0){

    }[
        "guarded": protected
    ]=>array(1){
        [
            0
        ]=>string(1)"*"
    }[
        "dates": protected
    ]=>array(0){

    }[
        "touches": protected
    ]=>array(0){

    }[
        "observables": protected
    ]=>array(0){

    }[
        "with": protected
    ]=>array(0){

    }[
        "morphClass": protected
    ]=>NULL[
        "exists"
    ]=>bool(true)[
        "softDelete": protected
    ]=>bool(false)
}string(2)"25"NULLNULL

编辑:根据Paras's comment

enter image description here

EDIT2: 使问题简单明了:

迁移:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Test extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tests', function($table)
        {
            $table->increments('id');
            $table->integer('22');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }

}

型号:

<?php
class Test extends Eloquent
{
}

控制器:

public function show()
{
    $tests = Test::all();
    foreach($tests as $test)
    {
        Log::info($test->id);
        Log::info($test->{'22'});
        Log::info($test->{"22"});
        Log::info($test->getAttribute("22"));
    }
}

数据表:

enter image description here

和日志:

[2017-02-25 09:16:48] production.INFO: 1 [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO: 2 [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []
[2017-02-25 09:16:48] production.INFO:  [] []

13 个答案:

答案 0 :(得分:9)

您可以使用以下语法,如PHP文档中的variable variables topic所示:

$obj->{'22'};
  

...

     

也可以使用大括号,以清楚地界定属性名称。当访问包含数组的属性中的值时,它们最有用,当属性名称由多个部分组成时,或当属性名称包含无效的字符时(例如来自json_decode())或SimpleXML)。

答案 1 :(得分:4)

试试这个:

$obj->getAttributeValue("22");

如果错误无效,请发布错误

答案 2 :(得分:4)

最好的方法是不要将Integer用作字段名。这是不好的实践。 但是如果需要,您应该使用raw方法访问数据库:

public function show()
{
     $tests = DB::table('test')
        ->select("22 as twentytwo")
        ->get();
    foreach($tests as $test){
        Log::info($test->twentytwo);
    }
}

答案 3 :(得分:3)

试试这个:

$col = '22';
$res = $obj->{$col};
var_dump($res);

答案 4 :(得分:3)

如果你总是知道名字是22,你可以这样做。

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

我对它进行了测试,它正确地返回了22字段中的值。

答案 5 :(得分:2)

您可以使用模型属性$ maps为麻烦的列添加不同的名称。尝试

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

$hidden = ['22'];

$appends = ['twentytwo'];

然后使用您的模型实例

echo $model->twentytwo;

答案 6 :(得分:2)

$arr= Tablename::where('id', 1)->lists('22', 'id')->toArray();
$result = $arr[1];

As 1 is the $id var. I tried it in my localhost and it works

答案 7 :(得分:2)

问题与此类似:

Hide number field from Eloquent model in Laravel

目前在Laravel中无法实现这一点,如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;
}

这是黑客。

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

问题已在此讨论:

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

答案 8 :(得分:1)

how can I use exists column with laravel model

可能重复

同样的答案适用于此;您可以使用$model->getAttribute('22')来获取模型属性的值。

答案 9 :(得分:1)

尝试使用以下位置: Tablename::where('22','=','value')->first();

答案 10 :(得分:1)

javax.persistence:Entity

答案 11 :(得分:1)

我知道这是几年前的问题,但希望有人觉得这有帮助,如果您将数据库表列名称设置为“数字”或“整数”,则可以像这样获取其数据;

在您的控制器示例中:

$your-table = users::all(); //或使用查找等。

//然后循环

foreach ($your-table 作为 $key) {

返回 $key['1'];

//['1'] 是我设置为整数的数据库列名

}

答案 12 :(得分:0)

尝试使用pluck()

$plucked = $collection->pluck('22');

$plucked->all();