Laravel Relationships 2表

时间:2014-03-28 15:52:31

标签: orm laravel laravel-4

我有两个表要连接,

First table = Friendship
ID
User1 = Tim 
User2 = Johny
Accepted = 0/1 <- friends if accepted = 1

Second table = Rooms
ID
Owner 
Room_ID
Roome_name

我的目标是让所有Johny朋友检查他们是否有房间,如果是检索所有者,room_id,room_name。我在谷歌搜索结果但我找不到它。这是我第一次与人际关系,我不知道如何使用那里的法律。对于简单明了的建议,我会很感激。

以下是我的课程:

class Friendship extends Eloquent {
    protected $table = 'friendship';

    public function friendrooms()
    {
        return $this->hasMany('Room');
    }
}

class Room extends \Eloquent {    
    protected $table = 'rooms';

    public function roomowner()
    {
        return $this->belongsTo('Friendship');
    }
}

抱歉我的英语不好。

2 个答案:

答案 0 :(得分:1)

假设您有一个用户表,您希望将您的朋友表用作用户自己的数据透视表。这听起来很复杂,但最终在实践中很容易......

我修改了一些列,因为有一些事情没有多大意义。不确定为什么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个房间的逻辑并不属于这里。当允许他们创建房间时,这将是一个验证问题。

答案 1 :(得分:0)

Eloquent中的所有美丽。你不必把where放在任何地方!你只需要打电话给

$friends = Friendship::find($friend_id);
$friends->friendrooms()->get(); //To get a list of all rooms

...是的, 那么简单

你放置belongsTohasMany的第二个,Eloquent已经告诉Laravel它应该分别对查询执行一种操作:where id = 'child_id'where = foreign_id = "id"。我不知道自己是否已经说清楚了。有任何疑问,只需评论! = d