【问题标题】:Eloquent relationship: return just one value not entire row雄辩的关系:只返回一个值而不是整行
【发布时间】:2020-09-28 13:43:03
【问题描述】:

在我的 laravel 项目中,我建立了一个评论部分,并希望在他们的评论旁边显示评论的人的姓名。

最初我只有用户 ID,所以我建立了一个关系 (hasOne) 将 comment 表 (comment & authorID) 链接到 users 表 (id (authorID)和用户名)

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();

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

我怎样才能做到这一点?

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    请尝试:

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

    【讨论】:

      猜你喜欢
      • 2018-04-11
      • 2017-07-29
      • 2015-12-17
      • 1970-01-01
      • 2018-06-19
      • 2021-12-15
      • 2013-04-10
      • 2020-09-08
      • 2014-10-23
      相关资源
      最近更新 更多