繁体   English   中英

我怎样才能在Laravel的Eloquent中代表这个游戏所有者关系

[英]How can I represent this Game Owner Relationship in Laravel's Eloquent

我试图弄清楚我遇到的逻辑问题,我不知道还有什么要问的!

我有两个对象,我试图描述它们之间的关系; UserGame 所以,现在,我有一个User属于许多Games ,并且一个Game属于许多Users 我想要描述的是User拥有Game时的特殊情况。 据推测,这只是owner_id表中的一列。 然而,我正在努力确定如何在Eloquent中表达这一点。 我是否需要为游戏所有者创建一个新对象? 或者我可以使用某种用户角色来描述这个吗?

游戏

class Game extends Eloquent 
{
    protected $guarded = array();
    public static $rules = array();

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

    // Need to identify the owner user.
}

用户

class User extends Eloquent
{
    protected $guarded = array();
    public static $rules = array();

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

我甚至难以弄清楚如何以清晰简洁的方式提出这个问题,所以如果需要更多细节,请不要犹豫。

你需要的是桌子:games_owners。 这是它的迁移模式:

Schema::create('games_owners', function($table)
{
    $table->increments('id');
    $table->integer('user_id');
    $table->integer('game_id');
    $table->timestamps();
});

这将是您的用户模型:

class User extends Eloquent
{
    protected $guarded = array();
    public static $rules = array();

    // User belongsToMany Game
    public function games()
    {
        return $this->belongsToMany('Game', 'games_owners', 'user_id');
    }
}

而你的游戏模型:

class Game extends Eloquent 
{
    protected $guarded = array();
    public static $rules = array();

    // Game belongsToMany User
    public function users()
    {
        return $this->belongsToMany('User', 'games_owners', 'game_id');
    }

    // Need to identify the owner user.
}

然后你就可以做到这样的事情:

$user = User::find(1);

foreach($user->games as $game) {
    echo $game->name;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM