Two foreign keys on how to map with an eloquent caravan

I have two tables in MySQL where the first is called users and the second is called games. The structure of the table is as follows.

of users

  • id (primary)
  • Email
  • password
  • real_name

games

  • id (primary)
  • user_one_id (foreign)
  • user_one_score
  • user_two_id (foreign)
  • user_two_score

My game table contains two external relationships for two users.

My question is how to make model relationships for this table structure? - According to the laravel documentation , I have to make a function inside the model and associate it with my relationships

eg

public function users() { $this->belongsTo('game'); } 

however, I cannot find anything in the documentation telling me how to deal with two foreign keys. as in my table structure above.

Hope you can help me along the way here.

thanks

+9
sql php mysql eloquent laravel
source share
2 answers

Migration:

 $table->integer('player1')->unsigned(); $table->foreign('player1')->references('id')->on('users')->onDelete('cascade'); $table->integer('player2')->unsigned(); $table->foreign('player2')->references('id')->on('users')->onDelete('cascade'); 

And the model:

 public function player1() { $this->belongsTo('Game', 'player1'); } public function player2() { $this->belongsTo('Game', 'player2'); } 

EDIT changed the 'game' to 'Game' as the user suggested deczo.

+15
source share

Unfortunately, the way you have this setting is unlikely to work in the current context. You may be more fortunate with the belongsTo method, but again, that only supports one relation.

You can implement the user1 () property owned by user2 (), and finally just declare a non-eloquent function to return both (something like $ users = array ($ this-> user1 (), $ this-> user2 ( )))

0
source share

All Articles