0

我有这样的架构:

图式

现在我想在 Laravel 4 中使用它。到目前为止,我只能实现为某些用户获取游戏,而无需触摸owntype. 代码:

public function games() {
     return $this->belongsToMany('Game','games_users','owntype_id','games_id')->where('user_id','1');
}

我得到的唯一的东西是onwtype_id。如何将owntype表格添加到“方程式”?

4

1 回答 1

0

withPivot您可以通过关系函数上的函数指定它们来访问额外的数据透视表列。

基本上我认为你想这样做:

class User extends Eloquent {

    public function games()
    {
        return $this->belongsToMany('Game', 'games_users')->withPivot('owntype_id');
    }

}

class Game extends Eloquent {

    public function users()
    {
        return $this->belongsToMany('User', 'games_users')->withPivot('owntype_id');
    }

}

class Owntype extends Eloquent {

    protected $table = 'owntype';

}

// Now you can do:
foreach ($user->games as $game)
{
    // Echo each Owntype description.
    echo Owntype::find($game->pivot->owntype_id)->description;
}

作为记录...我认为您可能会为owntype. 只需将描述设置为type数据透视表上的列即可。还要确保你的数据透视表被命名game_user(单数,按字母顺序),Laravel 会自动知道要使用哪个数据透视表。

class User extends Eloquent {

    public function games()
    {
        return $this->belongsToMany('Game')->withPivot('type');
    }

}

class Game extends Eloquent {

    public function users()
    {
        return $this->belongsToMany('User')->withPivot('type');
    }

}

// Now you can do:
foreach ($user->games as $game)
{
    // Echo each ownership type.
    echo $game->pivot->type;
}

可以在Laravel 4 文档中找到有关使用数据透视表的更多信息。

于 2013-05-16T11:44:16.553 回答