mardi 1 mars 2016

Laravel 5 Json with relationship

I have this code, is a tale with relathioship it self:

Category Model

class Cateogry extends Model {
    public function subCategory(){
        return $this->hasMany('\App\SubCategory');
    }
} 

SubCategory Model

<?php
class SubCategory extends Model {
    public function Category(){
        return $this->belongsTo('\App\Category');
    }
} 

In your controller

SomeController

<?php 

class SomeController extends Controller {
    public function index(){
        return Category::with('subCategory')->get()
    }
} 

when i do the return Category::with('subCategory')->get(); he prints:

{
            "id": 43,
            "name": "Quartos",
            "subcategories_id": null,
            "sub_category": [
                {
                    "id": 43,
                    "name": "Quartos",
                    "subcategories_id": null
                }
            ]
        }
    {
        "id": 55,
        "name": "Jovenil",
        "subcategories_id": 2,
        "sub_category": [
            {
                "id": 55,
                "name": "Jovenil",
                "subcategories_id": 2
            }
        ]
    }

instead:

{
            "id": 43,
            "name": "Quartos",
            "subcategories_id": null,
            "sub_category": [
                {
                    "id": 50,
                    "name": "Casal",
                    "subcategories_id": 1
                }
                {
                    "id": 51,
                    "name": "Jovenil",
                    "subcategories_id": 2
                }(...)
            ]
        }

why the quer does that?



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

Aucun commentaire:

Enregistrer un commentaire