php - 如何在 laravel 5.3 上从 user_id 获取用户名?

标签 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']));
}

这是来自 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/

相关文章:

php - 检查表中的 mysql 列是否有 php 中的重复项

php - 如何从表中选择全部并跳过具有特定值的某些行

php - 如何使用 Laravel Mix Setup 将 Laravel 数据传递到 Vue 根实例

php - 在一对多关系 laravel 5 中保存多条记录

laravel - 如何使用/PHP在服务器上预渲染Vue 2

laravel-5 - 在同一组下添加路由类别的更好方法

javascript - 我无法让 php 使用 onclick() 进行重定向

javascript - 添加选项以选择 PHP 中回显的每一行

php - 发送电子邮件在浏览器中测试虚假数据

mysql - laravel 子查询 whereIn 和最大值