获取多对多关系的最新数据

时间:2018-10-24 11:05:46

标签: php laravel-5

我有3张桌子,它们是:

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 |
+-------------------+-----------------------------+

这些表之间的关系是monitoringpost n<->n periodic_datamonitoringpost 1<->n post_dataperiodic_data 1<->n post_data

假设我已经有了这些表的模型,如何获取插入到value的最后一个post_data?我不知道该如何处理。这是当前代码:

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

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

和响应:

[
  {
    "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
  },

  ....
]

PS:我正在使用Laravel 5.4

0 个答案:

没有答案