model relationship ( use 3 models )

:open_hands: Hello ! guys i have a question about model relationship

I Have 3 Tables

  • Games (game_id , name)
  • Teams (team_id , name)
  • UserTeams (user_id , game_id)

User has a diffirent TeamGames

I want to get the teams of User by user_id

So the result wanted :

  • user_id:1 -> teams (( +team_a [ games : csgo , cod ] +team_b [games : csgo ] ... ))

Any Suggestions please ? (by using Model's)

You want a many-to-many relationship: https://docs.phalcon.io/3.4/en/db-models-relationships#defining-relationships

So in your UserTeams model:

function initialize(){
    $this->hasManyToMany(
        'game_id',
        'Games'
        'game_id','name',
        'Teams',
        'team_id'
}

Then using that relationship:

$UserTeam = UserTeams::find($some_random_user_id);
$Teams = $UserTeam->Teams;

Oh ! i think that its !

Thanks

i noticed that i forget the important key

  • UserTeams (user_id , game_id , team_id)*

so manyToMany .. will not be the same !

If UserTeams has a direct connection to the Team, then there's no need for a many-to-many relationship. You can use a hasOne(). That documentation page I linked to has information on that type of relationship as well.

Okey

i forget to specify that .. i need to UsersTeams Rows ( duplicate team_id its okey ) but not a duplicate of Teams Rows (team_id)

for example : userteams :

  • user_id-1 team_id-1 game_id-2
  • user_id-1 team_id-1 game_id-2

    if i use : hasMany/hasOne this will give me 2 duplicate of Team (team_id-1) ??

hasMany() is used when you have 1 of one model that has many of another model.

So a single Team would have many Games.

Your example has 2 identical rows - is that the data in your userteams table? It might be easier to explain and read if you put the information into a proper table when posting.

edited Jun '20

Omggggggggggg I lose all the comments when I submitted :( that suck...

sorry I write the bad example, ( im tired from coding all the day :( thats why i forget a lot hehe ) I forget change game_id

This is my data (usersteams):

  • user_id-1 team_id-1 game_id-2
  • user_id-1 team_id-1 game_id-3
  • user_id-2 team_id-1 game_id-3

this is the result i want :

+Teams :

  • team 1 (mode Teams)
    • info (name , title ...)
    • games (model Games):
      • game 2 : all usersteams in same team&game
      • game 3 : all usersteams in same team&game

Sorry for not explaining well Because of my level in English ♥