Laravel,获取单个记录的关联关系($first on a with())

3
我想在我的$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 中?
谢谢。

你需要用户信息还是仅相关数据? - SystemGlitch
4个回答

6
你正在尝试获取所有用户的数据,连同相关的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');

希望这能有所帮助。

您好。我已经有了 $user 对象,实际上我正在解析它。我想要添加 user_profile 关联。 - Leon
没错,就是这样! $user->load('user_profile'); 非常好 :) 急切加载...更快。 - Leon

1
你可以像这样做:
$user = User::with('user_profile')->where('id',$user_id)->first();
$user_profile_data = $user->user_profile;

0

请尝试以下查询

这里的$user_id是要获取其数据的用户的ID。

User::where('id', $user_id)->with('user_profile')->first()

在这里,您必须在用户模型中定义user_profile关系


0

尝试使用以下代码获取相关的user_profile

$userdata = $user->user_profile;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接