Thursday, 10 January 2019

Query where there is at least 1 association, but return all

I have created this record which you can see has 2 tags - tag1, and tag2

{
  "id": "d87de1d9-b048-4867-92fb-a84dca59c87e",
  "name": "Test Name",
  "tags": [
    {
      "id": "fa0ca8fd-eff4-4e58-8bb0-a1ef726f01d4",
      "name": "tag1",
      "organizationId": "d87de1d9-b048-4867-92fb-a84dca59c87e",
      "updatedAt": "2018-12-05T18:53:56.867Z",
      "createdAt": "2018-12-05T18:53:56.867Z"
    },
    {
      "id": "66e758af-9907-4278-8c4f-f8fb2bf9aea9",
      "name": "tag2",
      "organizationId": "d87de1d9-b048-4867-92fb-a84dca59c87e",
      "updatedAt": "2018-12-05T18:53:56.867Z",
      "createdAt": "2018-12-05T18:53:56.867Z"
    }
  ],
  "updatedAt": "2018-12-05T18:53:56.860Z",
  "createdAt": "2018-12-05T18:53:56.860Z"
}

I want to write a query that looks for an organization that contains tag1 and return that entire organization including all of the tags.

I currently have this query which only returns the tag record for which matches the query rather than all the tags.

db.organization.findAll({
  include: {
    model: db.tag,
    where: { name: 'tag1' }
  }
})

and it's producing this result

[
  {
    "id": "3d03d74e-82ec-485e-aa29-abe9e8b0f0e9",
    "name": "Test Name",
    "createdAt": "2018-12-05T19:29:40.685Z",
    "updatedAt": "2018-12-05T19:29:40.685Z",
    "tags": [
      {
        "id": "75dc9cd2-5e20-4aa6-b86e-cbaa2c896d57",
        "name": "tag1", <-- NOTE THAT ONLY TAG1 IS IN THE RESULTS EVEN THOUGH THERE SHOULD BE ANOTHER TAG OBJECT RETURNED
        "createdAt": "2018-12-05T19:29:40.694Z",
        "updatedAt": "2018-12-05T19:29:40.694Z",
        "organizationId": "3d03d74e-82ec-485e-aa29-abe9e8b0f0e9"
      }
    ]
  }
]

How can I write a query to do this?



from Query where there is at least 1 association, but return all

No comments:

Post a Comment