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

这个错误见

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

4

1 回答 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

于 2020-03-31T12:33:08.527 回答