这个问题在这里已有答案:
我正在使用Laravel 5.5。
我正在尝试使用Laravel的查询生成器获取对象实例。
public function functionName(Request $request) {
$seance = Seance::where('id_seance', '=', $request->idSeance)->get();
return $seance->type_seance;
}
我的模特:Seance(id_seance, type_seance, capacite_seance, niveau_seance, avec_coach, date_seance, heure_seance)
。
但是我收到此错误:
例外:此集合实例上不存在Property [type_seance]
感谢帮助!
Get()
方法返回一个集合对象,它就像一个数组,你需要使用first
方法来获取第一个对象:
public function functionName(Request $request) {
$seance = Seance::where('id_seance', '=', $request->idSeance)->first();
return $seance->type_seance;
}
您也可以使用find()方法,但id_seance
应该是表的主键:
$seance = Seance::find($request->idSeance);
return $seance->type_seance;
使用first()
而不是get()
来获取对象而不是对象集合:
$seance = Seance::where('id_seance', $request->idSeance)->first();
here解释了这些方法之间的区别。
使用get()
方法时,它将返回collection
而不是模型的实例。我建议改用first()
方法。
更好的是,使用Seance::find($request->idSeance)
或Seance::findOrFail($request->idSeance)
。这假设您已正确定义了模型上的主键。