@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']));
}
这是来自 Controller 的代码
我已经建立了关系
//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();
});
}
最佳答案
替换
public function user()
{
return $this->belongsTo('App\User');
}
与
public function user()
{
return $this->belongsTo('App\User','id','user_id');
}
在产品型号中。 并且在 Controller 中使用 get() 而不是 all()。
$products = Product::get();
更新:
在 Prodcut.php 中,您的 user() 方法不返回关系类型。您没有注意到我之前发布的答案,看看您的 user() 方法和我之前发布的方法之间的区别。您的方法需要返回
关系类型。
替换
公共(public)函数 user()
{
$this->belongsTo('App\User');
}
与
公共(public)函数 user()
{
return $this->belongsTo('App\User');
}
在 Product.php 中并使用 $product->user->name
访问 View 中的用户名
关于php - 如何在 laravel 5.3 上从 user_id 获取用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43834993/