Patchesoft
Patchesoft

Reputation: 317

Laravel joining two models to User model

I have the following tables:

Users Games Characters

A user will have one active game at a time, and from that game, will have one active character.

I want to perform the following joi on my authentication table:

SELECT * FROM users 
LEFT OUTER JOIN games ON games.ID = users.active_gameid
LEFT OUTER JOIN characters ON characters.ID = games.active_charid

Try to ignore the SELECT * part.

I'd like to perform these joins on my Auth table as soon as the page loads, so I have been using my User model to do the following:

class User extends Eloquent implements UserInterface, RemindableInterface {

    public function game() {
        return $this->hasOne('game', 'ID', 'active_gameid');
    }

}

class game extends Eloquent {

    protected $table = "games";

    public function character() {
        return $this->hasOne('character', 'ID', 'active_charid');
    }

}

class character extends Eloquent {

    protected $table = "characters";

}

The above doesn't work as outputting the following just returns a NULL value:

var_dump(Auth::user()->game->character);

I have tried to do the obvious checks such as making sure the data is in the table and such and that all seems fine.

Does anyone have any help on where I'm going wrong?

Thank you!

Upvotes: 2

Views: 2715

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Your relations are wrong:

// User model
public function game()
{
  return $this->belongsTo('Game', 'active_gameid', 'ID');
}

// Game model
public function character()
{
  return $this->belongsTo('Character', 'active_charid', 'ID');
}

and obviously it won't call your query, but 2 separate queries:

Auth::user()
  ->game // SELECT * FROM games WHERE ID = ?
  ->character; // SELECT * FROM characters WHERE ID = ?

Upvotes: 1

Related Questions