我使用此代码,但无法在相关产品中向用户发送名称我使用此代码
Creator: {{$product->users->name ?? ''}}
我无法显示产品的创建者对于productscontroller,我使用此:
public function index(){
$products = Product::with(['users'])->get();
return view('products.index', compact('products'));}
和用于模型产品
public function users()
{
return $this->belongsTo(User::class);
}
并且对于模型用户
public function products()
{
return $this->hasMany(Product::class);
}
和表
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedInteger('user_id');
$table->text('description');
$table->integer('weight');
$table->integer('price');
$table->timestamps();
});
此错误请参阅
试图获取非对象的属性“名称”(视图:
您需要在迁移中设置外键:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users'); // <- HERE
$table->text('description');
$table->integer('weight');
$table->integer('price');
$table->timestamps();
});
并且您的关系应命名为user
(单数)而不是users