mercredi 24 octobre 2018

get last data of many to many relationship

I have 3 tables, they are:

monitoringpost

+----------------+--------------------------------+
|    Column      |              Type              | 
+----------------+--------------------------------+
|id              | integer                        |
|nama_pos        | character varying(255)         |
|jenis           | character varying(255)         |
|sungai          | character varying(255)         |
|desa            | character varying(255)         |
|kec             | character varying(255)         |
|kab             | character varying(255)         |
|didirikan_oleh  | character varying(255)         |
|didirikan_tahun | integer                        |
|ka_jenis        | character varying(255)         |
|ka_pasang_ta    | character varying(255)         |
|ka_keterangan   | character varying(255)         |
|south           | character varying(255)         |
|east            | character varying(255)         |
|created_at      | timestamp(0) without time zone |
|updated_at      | timestamp(0) without time zone |
|mapping_code    | character varying(255)         |
|group           | character varying              |
+----------------+--------------------------------+

periodic_data

+--------+-------------------+
| Column |       Type        |
---------+-------------------+
| id     | integer           |
| uom_id | integer           |
| name   | character varying |
+--------+-------------------+

post_data

+-------------------+-----------------------------+
|      Column       |            Type             |            
+-------------------+-----------------------------+
| id                | bigint                      |
| monitoringpost_id | integer                     |
| periodic_data_id  | integer                     |
| extern_id         | character varying           |
| value             | double precision            |
| fetched_at        | timestamp without time zone |
+-------------------+-----------------------------+

the relation between those table are monitoringpost n<->n periodic_data, monitoringpost 1<->n post_data and periodic_data 1<->n post_data.

suppose that I already have the models for those table, how to fetch last value inserted to the post_data? I don't have idea how to deal with it. here is current code:

public function loadByType(Request $request, $type){
    $posts = MonitoringPost::with('data_periodic')->where('jenis', $type)->get();

    return response()->json($posts);
}

and the response:

[
  {
    "id": 334,
    "nama_pos": "B.Tub 0",
    "jenis": "PDA",
    "sungai": "STB",
    "desa": "",
    "kec": "",
    "kab": "",
    "didirikan_oleh": "",
    "didirikan_tahun": null,
    ...
    "data_periodic": [] // I want this property also contain last inserted value of its periodic data
  },

  ....
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire