miragejs / discuss

Ask questions, get help, and share what you've built with Mirage
MIT License
2 stars 0 forks source link

hasMany to hasMany (manyToMany) fixture associations not created #47

Open benswinburne opened 4 years ago

benswinburne commented 4 years ago

This may not be a bug, but the example in the docs

If this happens to be a bi-directional relationship

  models: {
    user: Model.extend({
+     posts: hasMany()
    }),

    post: Model.extend({
      author: belongsTo("user"),
    }),
  },

then Mirage will add an array of foreign keys for the new hasMany association.

I have a many to many relationship

creative: Model.extend({
  campaigns: hasMany(),
}),

campaign: Model.extend({
  creatives: hasMany(),
}),

And some fixtures

  {
    id: '48dc4215-6f6c-470c-8c3e-40d95311ef19',
    name: 'Example',
    creativeIds: [
      '3fd34999-9519-42b0-8f08-1c2dfea8d338',
      '247c689a-8834-4b64-a052-b73228bdb407',
    ],
  },

When querying the campaigns, I can see the two creatives, but when querying the creatives, I can't see the campaigns. Is this expected behaviour or a bug?

samselikoff commented 4 years ago

Sorry about the delayed response! I'm behind on issues a bit due to some consulting/training work.

In this case you would need to add the fixture data on both sides. So, you would need to add campaignIds to the creative fixtures.

Alternatively you could use seeds() hook and use the schema methods, in which case Mirage will take care of some of the bookkeeping for you:

seeds(server) {
  let c1 = server.create("creative", attrs);
  let c2 = server.create("creative", attrs);

  server.create("campaign", { name: "example", creatives: [c1, c2] });
}

or, if you really wanted to use hard-coded ids for some reason (or had them from somewhere else),

seeds(server) {
  let c1 = server.create("creative", {
    id: "3fd34999-9519-42b0-8f08-1c2dfea8d338",
    ...otherAttrs
  });
  let c2 = server.create("creative", {
    id: "247c689a-8834-4b64-a052-b73228bdb407",
    ...othetrAttrs
  });

  server.create("campaign", {
    name: "example",
    creativeIds: [
      "3fd34999-9519-42b0-8f08-1c2dfea8d338",
      "247c689a-8834-4b64-a052-b73228bdb407"
    ]
  });
}