lundi 24 août 2015

Eloquent join 2 tables

I am building an api that outputs json

so what i have is 2 tables

Categories Table
    id
    name
    nameAR
    nameTR


Items table
    id
    category_id
    nameAR
    nameEN

i the json output to be exactly like this because the android application is already published and this API will replace a static json file

{
"name" : *Category name*,
"nameAR" : *Category Arabic name*,
"nameTR" : *Category Turkish name*,
"items" : [

   {"nameAR": *Item Arabic name*,
   "nameEN": *Item English name*},

   {"nameAR": *Item2 Arabic name*,
   "nameEN": *Item2 English name*}

   ... etc
   ]
}

i know that i can do this:

$cat=Category::first();
$items=$cat->items;

to get every table in an individual variable but what i want is to get all categories with Category::all() and put all the items that belongs to the category as an object in an array called items in the category's object

*i do have my relationships configured

Category : 
    public function items()
        {
          return $this->hasMany('Project\Item');
        }


Item: 
    public function category()
        {
          return $this->belongsTo('Project\Category');
        }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KHzFLt
via IFTTT

Aucun commentaire:

Enregistrer un commentaire