Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

philipbaginski's avatar

Relationship problem.

Huston! I have got a problem :-)

I have a match model and would like to attach bet model to the match. I created bets table with match_id column, and matches table. I set up relations as bet->BelongsTo->match, and match->HasMany-> bets. And it works proper.

But I would like to attach the same bet to many matches. I did second set up with pivot table bet_match, and set up relations as bet->Belongs ToMany->matches, and match->Belongs ToMany->bets.

The problem I have got: On the match view page I'm able to attach existing bet, but I'm not able to create bet as with BelogsTo set up.

What kind of relation I should to use to solve it?

0 likes
4 replies
Nakov's avatar

@philipbaginski can you share some code please? Why can't you create a bet? I believe from what you said that the relationship is correctly setup now, which is many to many

$bet = new Bet;
// other bet fields..

$match->bets()->attach($bet);

this does not work?

philipbaginski's avatar

I'm not able to add code here. System is saying that it will be reviewed, but nothing happened.

philipbaginski's avatar

I have another resources connected via many-to-many relation - recource A can attach resource B, and recource B can attach recource A. The connection is done by pivot table - A_B, and it works proper.

In my case I started with connections: M - Match, and B - Bet. Many bets for single match, and every bet will belong to one match. This can by handled by: bet belongs to match, and match has many bets. The only connection beetween tables is additional column - match_id - in bets table. And from Match detail view I can create new bet. And I works proper.

But the problem I have got is: I would like to attach bet to MORE THAN ONE MATCH. So, the relation BelongsTo is usless and I have to make via many-to-many and pivot table. And I did it.

But it this case (many-to-many) I'm not able to create new bet from Match detail view. I'm only able to attach existing bet. This is crucial funcionality I need - create bet from Match view.

Bottomline: One unique bet can belong to one or more matches, and needs to be created from Match detail page.

Please or to participate in this conversation.