假设您有一个 users 表,您希望将 friends 表用作用户到其自身的数据透视表。这听起来很复杂,但实际上它最终很容易......
我修改了您的一些专栏,因为有些事情没有多大意义。不知道为什么rooms 需要一个 id 列和一个 room_id 列。这应该可以为您提供一个很好的基础,并且希望它对您来说是相当可扩展的。您可能需要一个 room_user 表来存储谁在哪个房间。
迁移
Schema::create('friends', function($table)
{
$table->increments('id');
$table->integer('user_id');
$table->integer('friend_id');
$table->boolean('accepted');
$table->boolean('deleted');
$table->timestamps();
});
Schema::create('rooms', function($table)
{
$table->increments('id');
$table->integer('user_id'); // The is room's owner.
$table->string('description');
$table->integer('room_id');
$table->string('room_name');
$table->timestamps();
});
用户模型
class User extends Eloquent implements UserInterface, RemindableInterface {
public function friends()
{
return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id')->wherePivot('accepted', '1');
}
public function room()
{
return $this->hasOne('Room');
}
public function hasRoom()
{
return (bool)$this->room()->count();
}
}
使用
$user = User::find(1);
foreach($user->friends as $friend) {
if($friend->hasRoom()) {
echo "<a href='javascript:location.href='ts3server://localhost/?port=9987&cid=".$friend->room->room_id."'>Join ".$friend->room->name."</a>";
}
}
如果您需要更多帮助,请尽管问。
编辑:
如果某人可以拥有多个房间,只需将该关系更改为 hasMany()。那么你将不得不使用它只是有点不同......
$user = User::find(1);
$friends = $user->friends()->paginate(15);
foreach($friends as $friend) {
if($friend->hasRoom()) {
foreach($friend->rooms as $room) {
echo "<a href='javascript:location.href='ts3server://localhost/?port=9987&cid=".$friend->room->room_id."'>Join ".$friend->room->name."</a>";
}
}
}
每天 3 个房间的逻辑并不真正属于这里。当允许他们创建房间时,这更像是一个验证问题。