laravel无法在相关产品中发送用户名

问题描述 投票:0回答:1

我使用此代码,但无法在相关产品中向用户发送名称我使用此代码

  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();
        });

此错误请参阅

试图获取非对象的属性“名称”(视图:

laravel laravel-5 eloquent laravel-4 laravel-7
1个回答
0
投票

您需要在迁移中设置外键:

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

© www.soinside.com 2019 - 2024. All rights reserved.