查询构建器获取模态实例[重复]

问题描述 投票:3回答:3

这个问题在这里已有答案:

我正在使用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]

感谢帮助!

php laravel laravel-query-builder
3个回答
2
投票

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;

2
投票

使用first()而不是get()来获取对象而不是对象集合:

$seance = Seance::where('id_seance', $request->idSeance)->first();

here解释了这些方法之间的区别。


2
投票

使用get()方法时,它将返回collection而不是模型的实例。我建议改用first()方法。

更好的是,使用Seance::find($request->idSeance)Seance::findOrFail($request->idSeance)。这假设您已正确定义了模型上的主键。

© www.soinside.com 2019 - 2024. All rights reserved.