0

My code..

ADONIS V4

With the code below I can generate exactly what I want as an output but I think I'm doing it the wrong way. I didn't find anything related on any forum, I believe I don't know what I'm looking for

  var results = await ReboxSurplus.query()
  .where(function () {
    if (state) this.where("state", state);
    if (city) this.where("city", city);
  })
  .with('port')
  .fetch();

  for (const row of results.rows) {
    row['prices'] = await ReboxPrice.query().where('state', row.state).where('city', row.city).where('port_car_id', row.port_car_id).fetch()
  }

My output..

The json I would like to obtain is exactly this, I believe that the solution would be to forget about this "enhancement" directly in the model, can someone help me?

 {
"id": 29305,
"port_car_id": 1,
"state": "RJ",
"city": "Rio de Janeiro",
"rebox_commission": 0,
"created_at": "2020-12-22 18:43:03",
"updated_at": "2020-12-22 18:43:03",
"prices": [
  {
    "id": 890641,
    "price": 125,
    "km": 10,
    "per_km": 1.5,
    "commission": 40,
    "created_at": "2020-12-21 13:59:59",
    "updated_at": "2020-12-21 13:59:59",
    "port_car_id": 1,
    "state": "RJ",
    "city": "Rio de Janeiro"
  },
  {
    "id": 890642,
    "price": 140,
    "km": 20,
    "per_km": 1.5,
    "commission": 40,
    "created_at": "2020-12-21 13:59:59",
    "updated_at": "2020-12-21 13:59:59",
    "port_car_id": 1,
    "state": "RJ",
    "city": "Rio de Janeiro"
  },
  {
    "id": 890643,
    "price": 160,
    "km": 40,
    "per_km": 1.5,
    "commission": 40,
    "created_at": "2020-12-21 13:59:59",
    "updated_at": "2020-12-21 13:59:59",
    "port_car_id": 1,
    "state": "RJ",
    "city": "Rio de Janeiro"
  }
],
"port": {
  "id": 1,
  "port": "Carro de Passeio",
  "percent_value": 40,
  "percent_extra": 0,
  "created_at": "2020-11-12 16:02:46",
  "updated_at": "2020-11-12 16:02:46",
  "state": null,
  "city": null
}

},

  • Do you use Adonis v4 or v5? – crbast Dec 23 '20 at 15:33
  • 1
    Im use v4, sorry! – Marco Antonio Dec 23 '20 at 17:13
  • Please read this : https://adonisjs.com/docs/4.1/relationships & https://adonisjs.com/docs/4.1/relationships#_adding_runtime_constraints . Can you share your db diagram (tables and relations) – crbast Dec 26 '20 at 13:41
  • I know the documentation well, but there is no key connection in my tables. Think of two sample tables "t1" and "t2" with the same fields in the two tables "city" and "state", being 1: t1 => n: t2 I would like my result to be: ```json { "t1": [ {t2}, {t2}, {t2} ] } ``` – Marco Antonio Dec 27 '20 at 14:32

0 Answers0