如何使用laravel中的"Shop"模型获取"users"表的"us



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表。它具有CCD_ 3,它是CCD_ 4表的外键。

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

这里我试图建立ShopUser之间的关系

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不存在。

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

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

最新更新