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

时间:2017-05-07 18:13:56

标签: php laravel 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',
];
}

这是两个

的表格架构
//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();
    });
}

0 个答案:

没有答案