首页 > 解决方案 > 雄辩的关系:只返回一个值而不是整行

问题描述

在我的 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();

这行得通,但它给了我每条评论的用户的整行。出于安全原因,我只想返回行(用户名)的“名称”字段,而不返回其余部分(电子邮件、时间戳等)。

我怎样才能做到这一点?

标签: laraveleloquentrelationship

解决方案


请试试:

$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' 是必要的,因为它负责关系


推荐阅读