简体   繁体   中英

Laravel: How to merge a Model into another Model

I'm using Lumen to create an API which has to handle 2 entities: Gamemaster and Player . Both of them are actually a User of my API since they have to provide a token. So at the end, 'gamemaster' and 'player' are just an 'user' role.

So I manage them using 3 Models that handle informations from the database (I keep it simple for the example):

  • User :
    • id
    • username
    • email
    • password
  • Gamemaster :
    • user_id (user id as foreign key)
    • created_games
    • ...
  • Player :
    • user_id (user id as foreign key)
    • registered_games
    • ...

So my question is: Is it possible to merge the Model User into Gamemaster and Player ? So that I can for example get a gamemaster email using Gamemaster::find($id)->email . Is there any way or I should each time search in both models to get all infos:

$user = User::find($id);
$userAsGamemaster = Gamemaster::where('user_id', '=', $id)->first();

$gamemasterName = $user->username;
$gamemasterEmail = $user->email;
$gamemasterCreatedGame = $userAsGamemaster->created_games;

use relations on model for this.

As in your case Gamemaster and Player both belongs to User so you can define relation on Gamemaster model and Player Model as following: ->

public function user(){
  return this->belongsTo('App\User', 'your_foregin_key', 'Your_local_key');
}

Now You can fetch email as follows: ->

$userAsGamemaster = Gamemaster::where('user_id', '=', $id)->first();
$email = $userAsGamemaster->user->email;

Or by using:

Gamemaster::find($id)->user->email;

That's all.

Okay. I write in an answer what we had been talking about in the comments.

Not answer to the question of merge two models, but you can achive what you want defining the relationship in your models Gamemaster and Player:

public function user()
{
  return $this->belongsTo(User::class);
}

So, if you have the User model id in the $id variable, you can do something like this:

$gamemaster = Gamemaster::where('user_id', $id)->first();

$gamemasterName = $gamemaster->user->username;
$gamemasterEmail = $gamemaster->user->email;
$gamemasterCreatedGame = $gamemaster->created_games;

And if in the $id variable you have the Gamemaster model id, you can do something like this:

$gamemaster = Gamemaster::find($id);

$gamemasterName = $gamemaster->user->username;
$gamemasterEmail = $gamemaster->user->email;
$gamemasterCreatedGame = $gamemaster->created_games;

And the same for the Player .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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