Laravel with() method, get all records from it

  laravel, php

I have a question related to getting some records or data from databases on Laravel. So I have this relationship in my Models.
For my VoteChoiceModel:

public function Theme(){
        return $this->hasMany('AppModelsVoteThemeModel', 'vote_themes_id', 'id');
}

and for my VoteThemeModel:

public function Choice(){
        return $this->belongsTo('AppModelsVoteChoiceModel', 'id', 'vote_themes_id');
}

then at my controller I have this code:

public function getParticipant(){
        $data = VoteThemeModel::select('*')->with('Choice')->get();
        return $data;
}

So in short if I run this I’ll get the reply of json like this:

"data": [
        {
            "name": "Theme-1",
            "banner": "Banner",
            "choice": {
                "id": 4,
                "name": "Doe Jhon",
                "icon": "PICT"
            }
        },
        {
            "name": "Theme-2",
            "banner": "-1620119938-Screenshot (1).png",
            "choice": {
                "id": 8,
                "name": "JhonDOO",
                "icon": "ICONIC"
            }
        }
    ]

As you can see the choice in json only return one data/records (In Theme-1 only Doe Jhon and Theme-2 is JhonDOO) while actually it contains more than one data/records. So in that ->choice I want to return all data that related to it.

Can someone help me to figure this out? I’m not so sure that I may have some mistakes at the relationship.

Thanks!!

Source: Ask PHP

LEAVE A COMMENT