jeudi 25 mars 2021

How to get data by query builder in laravel

I use join in query builder and here is the output

[
    {
        "id": 7,
        "name": "class 1",
        "idSubject": 17,
        "nameSubject": "Math"
    },
    {
        "id": 7,
        "name": "class 1",
        "idSubject": 16,
        "nameSubject": "history"
    },
    {
        "id": 8,
        "name": "class 2",
        "idSubject": 15,
        "nameSubject": "Computer"
    },
    {
        "id": 8,
        "name": "class 2",
        "idSubject": 19,
        "nameSubject": "geography"
    }
]

You can see id and name of class 1, 2 appearing twice. So, how to make it appear once.

this is my query:

    $data = DB::table('class')->join('class_subject','class.id','=','class_subject.class_id')
 ->join('subject','class_subject.subject_id','=','subject.id') 
->select('class.id','class.name','subject.id as idSubject','subject.name as nameSubject') ->get();

I want it:

[
    {
        "id": 7,
        "name": "class 1",
        "subject": [{"idSubject":"17","nameSubject: "Math"},
                    {"idSubject":"16","nameSubject: "history"}]
    }
]


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire