【问题标题】:How can I represent this Game Owner Relationship in Laravel's Eloquent我如何在 Laravel 的 Eloquent 中表示这种游戏所有者关系
【发布时间】:2014-01-12 03:00:40
【问题描述】:

我正试图梳理出我遇到的一个逻辑问题,但我不知道还能问哪里!

我有两个对象,我试图描述它们的关系; 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');
    }
}

我什至不知道如何以简洁明了的方式提出这个问题,所以如果需要更多细节,请不要犹豫。

【问题讨论】:

    标签: php laravel laravel-4 eloquent object-relational-model


    【解决方案1】:

    您需要的是这张桌子: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;
    }
    

    【讨论】:

    • 因此,从本质上讲,所有者-游戏关系是多对多的。对吗?
    • 是的。除非有人只为一个人创建游戏,否则它将始终是多对多关系。
    猜你喜欢
    • 2014-05-08
    • 2020-06-28
    • 1970-01-01
    • 2018-11-13
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    相关资源
    最近更新 更多