Search code examples
phplaravellaravel-4eloquentobject-relational-model

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


I'm trying to tease out a logical problem that I'm having and I didn't know where else to ask!

I have two Objects whose relationship I'm trying to describe; the User and the Game. So, right now, I have that a User belongs to many Games, and that a Game belongs to many Users. What I'm trying to describe is the special instance when a User owns a Game. Presumably, this would simply be a column in the table for the owner_id. I am, however, struggling to establish how I can represent this in Eloquent. Do I need to create a new Object for the Game owner? Or can I use some kind of User role to describe this?

Game

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.
}

User

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

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

I'm having difficulty even figuring out how to ask this in a clear and concise way, so if there's any more detail needed, please don't hesitate to ask.


Solution

  • What you need is thid table: games_owners. This is a migration schema for it:

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

    This would be your User model:

    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');
        }
    }
    

    And you game model:

    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.
    }
    

    And then you'll be able to do things like this:

    $user = User::find(1);
    
    foreach($user->games as $game) {
        echo $game->name;
    }