我正在使用此代码获取模型:
$user = \App\Http\Models\User::where('id', $id)->with('services')->get();
我想以此函数为例
$user->getServiceList(); //this metod gets ALL services, not hasMany
但它会导致错误方法getServiceList不存在
get()
加载一个集合,所以你需要迭代它来获取对象:
$users = \App\Http\Models\User::where('id', $id)->with('services')->get();
foreach ($users as $user) {
echo $user->getServiceList();
}
如果您按用户ID搜索,则使用find方法要好得多:
$user = \App\Http\Models\User::with('Service')->find($id);
$user->getServiceList();