我是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($aircraft)
时,我能够确认数据是否存在。在我看来,我可以通过循环访问该值,但我需要控制器中的这些数据来对另一个表执行第二次查询。
希望这是有道理的。干杯。
编辑
当运行
dd($aircraft)
时,我得到: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()
使用query builder
方法时,不管它得到多少记录,它都将返回一个数组。所以你可以通过索引来访问它。顺便说一句,别忘了检查一下是否空虚,以克服可能出现的错误。
$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;