首页 > 解决方案 > 如何在laravel中使用`Shop`模型获取`users`表的`user`的外键名称?

问题描述

shops桌子

         Schema::create('shops', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedBigInteger('user_id');

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->boolean('is_active')->default(false);
            $table->text('description')->nullable();
            $table->float('rating')->nullable();
            $table->unsignedBigInteger('location_id');

            $table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');

            $table->timestamps();
        });

这是shops桌子。它具有user_id哪个是users表的外键。

users桌子

         Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('photo')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->longText('cartitems')->nullable();
            $table->longText('wishlist')->nullable();
            $table->unsignedBigInteger('discount')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });

这是users桌子

Shop模型(关系)

public function seller()    //user --> seller
{
        return $this->belongsTo(User::class, 'user_id');
}

在这里,我尝试建立和之间的Shop关系User

DashboardController

public function shops()
{
    $shops = Shop::all();

    dd($shops->seller()->name);
}

在这里我想获取seller商店的名称

What I am getting after run the project

BadMethodCallException 方法 Illuminate\Database\Eloquent\Collection::seller 不存在。

标签: phpdatabaselaravelrelationshipquery-builder

解决方案


$shops 是一个集合。它是 Shop Model 实例的集合。卖家是店铺模型的关系。

foreach($shops as $shop){
    echo $shop->seller->name;
}

推荐阅读