表示laravel中使用相同的两个模型但用途不同的两种关系



我在laravel中有两个模型,用户模型和房间模型。每个用户可以属于多个房间,每个房间内有多个用户。

我还想保存创建房间的用户创建一个名为admin_id的字段.

这将创建两个关系,一个多对多关系(房间和用户)和一个一对多关系(用户和用户创建的所有房间)

我的问题是,我不知道如何建模这些信息,我试图创建一个名为users_rooms的单独表,并添加创建表的用户id作为房间表内的外键,但这打乱了我的模型关系函数。

Schema::create('rooms', function (Blueprint $table) { //Rooms schema
$table->id();
$table->string('name');
$table->unsignedBigInteger('admin_id');
$table->timestamps();
$table->foreign('admin_id')
->references('id')
->on('users')
->onDelete('cascade');
});

Schema::create('users', function (Blueprint $table) {. //Users schema
$table->id();
$table->string('username');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('connected')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::create('user_room', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_id');
$table->foreign('user_id')
->references('id')
->on('users');
$table->foreign('room_id')
->references('id')
->on('rooms');
});

class Room extends Model

{
use HasFactory;  
public function users(){
return $this->belongsToMany(User::class,'user_room');
}
public function user(){
return $this->belongsTo(User::class);
}     
}

class User extends Authenticatable
{
use HasFactory; 
/*The problem comes here, i don't know how to name the 
functions to represent the both relationships*/
public function rooms(){
return $this->belongsToMany(Room::class,'user_room');
}
public function rooms(){
return $this->hasMany(Room::class);
}
}

首先您需要指定房间模型上的外键,因为它被命名为admin_id

class Room extends Model          
{
public function user()
{
return $this->belongsTo(User::class, 'admin_id');
}     
}

关系的命名与结构无关,所以你可以叫它什么,我可能会用一些与用户是管理员相关的东西。

class User extends Authenticatable
{
public function administrativeRooms()
{
return $this->hasMany(Room::class);
}
}

//为Room模型添加外键

class Room extends Model          
{
public function user()
{
return $this->belongsTo(User::class, 'admin_id');
}     
}  
class User extends Authenticatable
{
use HasFactory; 

public function rooms(){
return $this->belongsToMany(Room::class,'user_room');
}
// Then need to simply change method name rooms from something else
// as shown below    
public function roomsOwn(){
return $this->hasMany(Room::class);
}
}

那么你可以在eloquent中使用

// This will give you all users list with the rooms they have created
// and rented
User::with('roomsOwn', 'rooms')->get();

提示

无论何时创建数据透视表(就像这里创建了user_room),请尝试按字母顺序使用名称room_user。这样,Laravel自动猜测数据透视表的名称,我们不需要在查询中指定。

相关内容

  • 没有找到相关文章

最新更新