在我的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.comdocs7.xeloquent-relationships#eager-loading。
请注意,包括'id'是必要的,因为它负责的关系是