为每个专业创建Post的json

时间:2017-07-14 06:37:56

标签: laravel laravel-5 eloquent many-to-many

我有桌子

+============+  +=================+  +======================+
|    Post    |  |   Specialities  |  |   Speciality_post    |
+============+  +=================+  +======================+
|    title   |  |       id        |  |       post_id        |
+------------+  +-----------------+  +----------------------+
|    image   |  |   specialities  |  |     speciality_id    |
+------------+  +-----------------+  +----------------------+
|    post    |
+------------+

与多对多的关系

$newsjson = newspost::select('id','title','image','post','created_at')
            ->with([
                'specialities'=> function($query) {
                    $query->select('specialities');
                }
            ])->get();

我得到的是什么

{
    "id": 7,
    "title": "Post Title",
    "image": "public/VmbDObltSRiOfvpudgy72kK4xryDRIkYGJj0rsDq.jpeg",
    "post": "This is post",
    "created_at": "2017-07-14 05:59:28",
    "specialities": [
        {
            "specialities": "oncology"
        },
        {
            "specialities": "patholgy"
        },
        {
            "specialities": "cardiology"
        }
    ]

我想要的是

{
    "NEWS" : [
        {
            "id":7,
            "title":"Post Title",
            "image":"public\/VmbDObltSRiOfvpudgy72kK4xryDRIkYGJj0rsDq.jpeg",
            "post":"This is post",
            "created_at":"2017-07-14 05:59:28",
            "specialities:oncology"
        }, 
        {
            "title":"Post Title",
            "image":"public\/VmbDObltSRiOfvpudgy72kK4xryDRIkYGJj0rsDq.jpeg",
            "post":"This is post",
            "created_at":"2017-07-14 05:59:28",
            "specialities:pathology"
        },
        {
            "title":"Post Title",
            "image":"public\/VmbDObltSRiOfvpudgy72kK4xryDRIkYGJj0rsDq.jpeg",
            "post":"This is post",
            "created_at":"2017-07-14 05:59:28",
            "specialities:cardiology"
        }
    ]
}

0 个答案:

没有答案