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

标签 php mysql laravel eloquent

我想将一些相关的模型数据添加到我的 $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/

相关文章:

php - 使用 php 激活和停用 mysql 记录

php - 子查询中的group_concat

php - 如何在 Laravel 5.4 中使用 has-many-through 关系查询 3 个表

php - 将 HTML 转换为 PHP 后 CSS 背景图像失败

php - 在SQL中根据row_count使用Limit

php - 显示来自 WordPress 帖子自定义字段的图像

mysql - 不明确的字段名称/使用 FETCH_OBJ 添加表名称

php - 多表中的 Laravel 关系

php - sql中如何按月过滤

php - Laravel 路由不更新