【问题标题】:Laravel getting data from other table in view when you know the id当您知道 id 时,Laravel 从视图中的其他表中获取数据
【发布时间】:2016-06-19 19:28:43
【问题描述】:

我有一个表“reviews”,其中有一列名为“from_user”。所以基本上是放置评论的用户。在此列中,用户的 id 存储在 users 表中。是否可以在我的视图中找出用户名?

这就是现在的样子:

 @foreach($authUser->reviews as $review)
   <p>{{ $review->body }} - {{$review->from_user }}</p>
 @endforeach

所以这段代码现在显然显示了用户的 id。

这是我的用户表的样子:

ID |姓名 |用户名 | ...

这是我的评论表的样子:

ID |来自用户 | on_user |身体

所以我的评论表中的 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');
    }
}

【问题讨论】:

  • 可以提供用户模型吗?
  • @xdevnull 是的,结帐已编辑 OP

标签: php mysql laravel


【解决方案1】:

更新

在您的review model 中,您需要告诉关系使用什么外键。默认添加relationName_id

Eloquent 通过检查 关系方法的名称和方法名称的后缀 _ID。但是,如果 Phone 模型上的外键不是 user_id,您可以将自定义键名称作为第二个参数传递给 belongsTo 方法。 #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

【讨论】:

  • 我想我已经编辑了关系结帐 OP 我添加了我的用户模型
  • 我已经为Review 模型应用了关系。读取类名
  • 你能签出我编辑的 OP 我添加了我的用户和评论模型我的关系正确吗?
  • 非常感谢!这很简单:)
猜你喜欢
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2017-10-16
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2019-02-10
相关资源
最近更新 更多