如何从 laravel 5.3 上的 user_id 获取用户名?

how to get username from user_id on laravel 5.3?

@foreach($productChunk as $product)
  <div class="pull-left user_id">{{ $product->user_id }}</div>
@endforeach

目前这是我的代码。它目前显示上传该产品的用户 ID 如何让它显示上传者姓名?

public function getIndex()
{
  $products = Product::all();
  return view('shop.index', compact(['products']));
}

这是来自控制器的代码

我已经确定关系了

//Product.php
public function user()
{
  //$this->belongsTo(User::class);
  $this->hasOne('App\User');
}


//User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use Notifiable;

public function product()
{
  return $this->hasMany('App\Product');
}
protected $fillable = [
    'name', 'email', 'password',
];

protected $hidden = [
    'password', 'remember_token',
];
}

这是 table 两者的架构

//user
Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
//product
Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->text('description');
        $table->integer('price');
        $table->integer('category_id');
        $table->string('image')->nullable();
        $table->integer('user_id');
        $table->timestamps();
    });
}

您必须有两个模型 product.php 和 user.php。用户使用 user_id 字段链接到产品。

然后你只需要添加一个关系:

在产品型号中添加以下内容:

//Product.php
public function user()
{
  return $this->belongsTo('App\User');
}


//User.php
public function products()
{
  return $this->hasMany('App\Product');
}

现在在您的 blade 中,您可以执行以下操作:

@foreach($productChunk as $product)
  <div class="pull-left user_id">{{ $product->user->name }}</div>
@endforeach

在控制器中添加预先加载:

public function getIndex()
{
  $products = Product::with('user')->get();
  return view('shop.index', compact(['products']));
}

替换

public function user()
{
  return $this->belongsTo('App\User');
}

public function user()
{
  return $this->belongsTo('App\User','id','user_id');
}

在产品型号中。 并在控制器中使用 get() 而不是 all()。

$products = Product::get();

更新: 在 Prodcut.php 中,您的 user() 方法未返回关系类型。您没有注意到我之前发布的答案,请查看您的 user() 方法与我之前发布的方法之间的区别。您的方法需要 return 一种关系类型。

替换

public function user() { $this->belongsTo('App\User'); }

public function user() { return $this->belongsTo('App\User'); }

in Product.php 并使用 $product->user->name

在您的视图中访问用户名