4

So, I'm not super knowledge with MySQL relations, upserting and such. I'm looking for an explanation on how (if?) this is possible to do.

[
  {
    scheduledAt: '17:55',
    league: { name: 'Champions League - Group Stage' }
  },
  {
    scheduled_at: '19:45',
    league: { name: 'Champions League - Group Stage' }
  },
  {
    scheduled_at: '19:30',
    league: { name: 'Primera B Metropolitana' },
  },
  {
    scheduled_at: '21:00',
    league: { name: 'Primera B Metropolitana' }
  }
]

Say I wanted to insert this graph of data. The root objects are going into the fixtures table, and the league property is this relation in the Fixtures model.

{  
  league: {
    relation: Model.BelongsToOneRelation,
    modelClass: `${__dirname}/League`,
    join: {
      from: 'fixtures.league_id',
      to: 'leagues.id'
    }
  }
}

So, currently if I use insertGraph to insert all this data. It's inserts into both the fixtures and leagues table and relates as you would expect.

{
  "scheduled_at": "17:55",
  "league": {
    "name": "Champions League - Group Stage",
    "created_at": "2018-10-03T13:02:03.995Z",
    "id": 1
  },
  "league_id": 1
  "created_at": "2018-10-03T13:02:04.042Z",
  "id": 1
}

However if I insert the exact same league object, it will just create another duplicate league and fixture row with the next incremented ID (2 in this case).

Is it possible for it to find if a league exists with that name, and then use that row/ID as the league_id, like so:

{
  "scheduled_at": "17.55",
  "league_id": 1
  "created_at": "2018-10-03T13:02:04.042Z",
  "id": 2
}

Sorry if I've explained this horrendously. But I'm not so hot on the terminology so I don't know what I'm actually looking to do. I feel like this is a super easy thing, but maybe my structure or method is wrong.

tribe
  • 321
  • 2
  • 9

0 Answers0