[英]How can I get the foreign-key name of `user` of `users` table using `Shop` model in laravel?
shops
table 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();
});
Here is the
shops
table.这是
shops
的桌子。 And it hasuser_id
which is foreign key ofusers
table.它有
user_id
,它是users
表的外键。
users
table 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();
});
This is the
users
table这是
users
表
Shop
model (relatonship) Shop
model(关系)
public function seller() //user --> seller
{
return $this->belongsTo(User::class, 'user_id');
}
Here I try to make a relationship between
Shop
andUser
在这里,我尝试在
Shop
和User
之间建立关系
DashboardController
public function shops()
{
$shops = Shop::all();
dd($shops->seller()->name);
}
Here I want to get the name of the
seller
of the shop这里我要获取店铺
seller
的名字
What I am getting after run the project
BadMethodCallException Method Illuminate\Database\Eloquent\Collection::seller does not exist.
BadMethodCallException 方法 Illuminate\Database\Eloquent\Collection::seller 不存在。
$shops is a collection. $shops 是一个集合。 It's a collection of instances of Shop Model.
它是 Shop Model 实例的集合。 And seller is relation of Shop Model.
卖家是Shop Model的关系。
foreach($shops as $shop){
echo $shop->seller->name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.