我想将一些相关的模型数据添加到我的 $user 对象中。让我解释一下:
$user = User::find(1); // my user object
// I want to add my defined user profile from the user_profile relationship
$userdata = $user->with('user_profile')->first();
这不起作用 :( 它返回我的数据库中第一个用户的用户配置文件!
$user = User::find(1); // my user object
// I want to add my defined user profile from the user_profile relationship
$userdata = $user->with('user_profile')->get();
这也不是我需要的——在这种情况下,用户始终是单个记录,而不是集合。
那么如何获取$user的相关“with”数据,并存储到$userdata中呢?
谢谢。
最佳答案
您正在尝试通过预先加载获取所有具有关联 user_profile
的用户的数据。
User::with('user_profile')->get();
如果想获取单用户的数据可以试试。
User::with('user_profile')->where('id',$user_id)->first();
使用 with('relations')
将返回所有用户以及与他们相关的数据。
您现在可以从对象本身访问它们:
$user = User::with('user_profile')->where('id',$user_id)->first();
$userProfile = $user->user_profile;
如果 $user
已经获取并且您想要获取关联关系。
那你可以
$user->load('user_profile');
希望对你有帮助
关于php - Laravel,获取单个记录的关系($first on a with()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49979865/