php - 当您知道 id 时,Laravel 从 View 中的其他表中获取数据

标签 php mysql laravel

我有一个表“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/

相关文章:

PHP,如何编写更快的查询来更新大对象

c# - Mysql语句给出null

php - php中的sql不工作可能是编码?

Mysql暂时抑制唯一索引

拉拉维尔 4 : how can I put data into every view?

javascript - vue.js : Property or method "" is not defined, 渲染错误: "TypeError: Cannot read property ' ' of undefined"

php - 如何将上传的图片转换成JPG格式

php - 将多个选择选项放入 PHP 数组

php - Eloquent 中的一对多关系与 JSON 字段

php - Laravel Eloquent - 按枚举字段排序