我是新手,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();
Run Code Online (Sandbox Code Playgroud)
我想从中获取价值,aircraft.aircraft_id但这就是我遇到的问题。我试过了:
$id = $aircraft->aircraft_id;
Run Code Online (Sandbox Code Playgroud)
我试过了:
$id = $aircraft->aircraft.aircraft_id;
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
$id = array_get($aircraft, 'aircraft_id');
Run Code Online (Sandbox Code Playgroud)
但是我得到null了一种价值。当我执行var_dump($aircraft)或时,dd($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
}
]
}
Run Code Online (Sandbox Code Playgroud)
在上使用get()method时,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;
Run Code Online (Sandbox Code Playgroud)
如果您执行查询,get()您将始终得到一个集合作为结果。即使您只需要一种型号。改变它的最简单方法是使用first():
$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)
->first();
$id = $aircraft->aircraft_id;
Run Code Online (Sandbox Code Playgroud)