![](/img/trans.png)
[英]Display the Name of Table using the ID of another table in Laravel Eloquent
[英]Display user name from another table Laravel 8
大家好,我有两张桌子
在列表中我有一些列,一个是 user_id,并且与用户表有关。 我想显示与用户表相关的用户名。 在索引刀片中,我使用了一些标签。 但是当我使用->rightjoin("users", "users.id", "=", "listings.user_id")
时它是有效的但是,连接破坏了我的标签使它们成为默认值,与其他帖子一样。
public function index(Request $request)
{
$listings = Listing::where('is_active', true)->with('tags')
//->rightjoin("users", "users.id", "=", "listings.user_id") //don't show tags of the posts
->orderBy('listings.created_at', 'desc')
->get();
//check if posts ar listing by last date or something
$tags = Tag::orderBy('name') // variable displayed in view
->get();
您可以像这样使用with
方法来获取相关user
public function index(Request $request) {
$listings = Listing::where('is_active', true)->with(['user', 'tags'])
->orderBy('listings.created_at', 'desc')
->get();
}
但请确保您将正确的关系添加到Listing
model 中,如下所示
public function user() {
return $this->belongsTo(User::class);
}
我推荐此代码用于 controller:
public function index(Request $request) {
return $listings = Listing::query()
->where('is_active', true)->with(['user', 'tags'])
->orderBy('listings.created_at', 'desc')
->get();
}
在模型部分,我建议你把这段代码:
public function user() {
return $this->belongsTo(User::class);
}
我建议您填写字段 foreignKey, ownerkey in relation: 如下例所示:
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.