mardi 28 novembre 2017

Laravel return object with nesting

Assume the following models:

class Character extends Model
{
    protected $fillable = ['items'];
    protected $guarded = ['id'];

    public function items(){
        return $this->hasMany("App\Item");
    }
}

class Item extends Model
{

    public function character(){
        return $this->belongsTo("App\Character");
    }

}

When a request is made, the controller performs the following:

public function getCharacter(Request $request, $characterID = 0){

        $characters = array(Character::find($characterID));

        foreach($characters as $key => $value){
            //ADD THE ITEMS
            $characters[$key]->items = $characters[$key]->items;
        }
        return $characters;
    }

------This works fine.
Im getting a character json with a member "items" that holds all the data for the corresponding item models.

However, assume Items didnt belong to Character but to ItemPackage. Specifically, Items belong to ItemPackage ( ItemPackage has many Items ) and ItemPackage belongs to Character ( Character has many ItemPackage(s) )

In a similar fashion, i tried performing the following in the controller but it doesnt work.

....
foreach($characters as $key => $value){
    //ADD THE ITEM
    $characters[$key]->itemPackages = $characters[$key]->itemPackages
    //the above line works but we also need to add the item obj data so:
        foreach($characters[$key]->itemPackages as $key2){
            $characters[$key]->itemPackages[$key]->arrayOfItems = "whatever here";
        }
    }
....

Specifically, i get an error of : Undefined offset: 1. Im clearly not understanding the data structures im operating on very well, maybe someone could illuminate me.

Thanks for taking the time



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire