如何从数据库中获取模型后调用函数?

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

我正在使用此代码获取模型:

$user = \App\Http\Models\User::where('id', $id)->with('services')->get();

我想以此函数为例

$user->getServiceList(); //this metod gets ALL services, not hasMany

但它会导致错误方法getServiceList不存在

laravel
2个回答
2
投票

get()加载一个集合,所以你需要迭代它来获取对象:

$users = \App\Http\Models\User::where('id', $id)->with('services')->get();
foreach ($users as $user) {
    echo $user->getServiceList();
}

2
投票

如果您按用户ID搜索,则使用find方法要好得多:

 $user = \App\Http\Models\User::with('Service')->find($id);

 $user->getServiceList();
© www.soinside.com 2019 - 2024. All rights reserved.