微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何从Laravel 5中的一个集合中获取一个项目?

我是Laravel的新手,我无法弄清楚如何从返回的集合中获取项目的价值.这是我的代码

$aircraft = Aircraft::join('pams_shared.shared_aircraft', 'aircraft.shared_aircraft_id', '=', 'pams_shared.shared_aircraft.shared_aircraft_id')
        ->select('aircraft.*', 'shared_aircraft.*')
        ->where('aircraft.owner_id',Auth::user()->owner_id)
        ->where('registration',$reg)
        ->get();

我想从aircraft.aircraft_id获取价值,但这就是我被卡住的地方.我试过了:

    $id = $aircraft->aircraft_id;

我试过了:

    $id = $aircraft->aircraft.aircraft_id;

我也尝试过:

    $id = array_get($aircraft, 'aircraft_id');

但我得到null作为一个值.当我执行var_dump($飞机)或dd($飞机)时,我能够确认数据是否存在.

在我看来,我能够通过循环访问该值,但我需要在我的控制器中的这些数据在另一个表上执行第二次查询.

希望有道理.干杯.

编辑

当运行dd($飞机);我明白了:

Collection {#239 ▼
#items: array:1 [▼
    0 => Aircraft {#240 ▼
            #fillable: array:8 [▶]
            #table: "aircraft"
            #primaryKey: "aircraft_id"
            #connection: null
            #perPage: 15
            +incrementing: true
            +timestamps: true
            #attributes: array:16 [▼
                "aircraft_id" => 5
                "owner_id" => 2
                "shared_aircraft_id" => 67443
                "year" => 2012
                "serial_number" => "C127RG3"
                "registration" => "C-SMTH"
                "created_by" => 2
                "modified_by" => 2
                "created_at" => "0000-00-00 00:00:00"
                "updated_at" => "0000-00-00 00:00:00"
                "aircraft_code" => "2072438"
                "aircraft_mfr" => "CESSNA"
                "aircraft_model" => "172RG"
                "aircraft_type" => 4
                "aircraft_eng" => 1
                "aircraft_cat" => 1
                ]
            #original: array:16 [▶]
            #relations: []
            #hidden: []
            #visible: []
            #appends: []
            #guarded: array:1 [▶]
            #dates: []
            #casts: []
            #touches: []
            #observables: []
            #with: []
            #morphClass: null
            +exists: true
        }
    ]
}

解决方法:

查询构建器上使用get()方法时,无论获取多少记录,它都会返回一个数组.因此,您可以通过索引指向它来访问它.顺便说一句,不要忘记检查空虚以克服可能的错误.

$id = 0;
$aircraft = Aircraft::join('pams_shared.shared_aircraft', 'aircraft.shared_aircraft_id', '=', 'pams_shared.shared_aircraft.shared_aircraft_id')
        ->select('aircraft.*', 'shared_aircraft.*')
        ->where('aircraft.owner_id',Auth::user()->owner_id)
        ->where('registration',$reg)
        ->get();
// Now you can access properties
if(count($aircraft) > 0) $id = $aircraft[0]->aircraft_id;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐