我有一个表“reviews”,其中有一列名为“from_user”。所以基本上是放置评论的用户。在此列中,用户的 ID 存储在用户表中。是否可以在我的 View 中找出用户名?
这是现在的样子:
@foreach($authUser->reviews as $review)
<p>{{ $review->body }} - {{$review->from_user }}</p>
@endforeach
所以这段代码现在显然显示了用户的 ID。
这是我的用户表的样子:
ID | NAME | USERNAME | ...
这是我的评论表的样子:
ID | from_user | on_user | body
所以我的评论表中的 from_user 等于我的用户表的 ID
所以我的问题是在我看来是否可以在我的 foreach 循环中访问我的用户名?
我是 laravel 的新手,所以非常感谢您的帮助!
提前致谢
编辑:用户模型
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, Messagable;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password', 'firstname', 'lastname', 'straat', 'postcode', 'plaats', 'provincie', 'role', 'specialisatie'];
protected $hidden = ['password', 'remember_token'];
public function projects()
{
return $this->hasMany('App\Project');
}
public function reviews()
{
return $this->hasMany('App\Review');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
EDIT2 我的评论模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Review extends Model
{
protected $guarded = [];
protected $table = 'reviews';
public function User()
{
return $this->belongsTo('App\User');
}
}
最佳答案
已更新
在您的审核模型
中,您需要告诉关系要使用什么外键。默认情况下,它添加 relationName_id
。
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method. #Source
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Review extends Model
{
protected $guarded = [];
protected $table = 'reviews';
public function user()
{
return $this->belongsTo('App\User', 'from_user');
}
}
在你看来
@foreach($authUser->reviews as $review)
<p>{{ $review->body }} - {{ $review->user->name }}</p>
@endforeach
关于php - 当您知道 id 时,Laravel 从 View 中的其他表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37911020/