laravel - 雄辩的关系:只返回一个值而不是整行
问题描述
在我的 laravel 项目中,我建立了一个评论部分,并希望在他们的评论旁边显示评论的人的名字。
最初我只有用户 ID,所以我建立了一个关系 (hasOne),将评论表 (comment & authorID) 链接到用户表 (id (authorID) & username)
Comment.php(模型)是:
[..]
public function author()
{
return $this->hasOne(User::class, 'id', 'Author');
}
User.php 模型是:
<?php
[..]
public function author()
{
return $this->hasMany(Comment::class, 'Author', 'id');
}
在控制器中,我通过以下方式获取数据:
$comments= Comments::where('LinkID', (string) $id)->with('author')->orderBy('updated_at', 'ASC')->get()->all();
这行得通,但它给了我每条评论的用户的整行。出于安全原因,我只想返回行(用户名)的“名称”字段,而不返回其余部分(电子邮件、时间戳等)。
我怎样才能做到这一点?
解决方案
请试试:
$comments= Comments::where('LinkID', (string) $id)->with(['author' => function ($q) {
$q = $q->select('name', 'id');
return $q;
}
])->orderBy('updated_at', 'ASC')->get()->all();
或其他方式:
$comments= Comments::where('LinkID', (string) $id)->with('author:id,name')->orderBy('updated_at', 'ASC')->get()->all();
请参阅急切加载(急切加载特定列部分)
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
请注意,包括 'id' 是必要的,因为它负责关系
推荐阅读
- json - 从字符串中删除空格 - 正则表达式
- hadoop - Hive 删除字符串之间的多个空格
- javascript - 更改 Outlook 的电子邮件主题
- powerbi - 使用 IF 或 ALLEXCEPT 求和
- html - 创建 html 链接以下载和安装配置文件
- android - Android Oreo 上的广播接收器
- javascript - 找不到图像/无法获取 /uploads/image nodejs REST API
- linux - 安装审计时出错
- c# - Payfast 通知 url 测试 c#
- javascript - 有什么方法可以读取 openlayers 4 中的 geojson 属性吗?