how to return a json response based on database relationship using eloquent

寵の児 提交于 2019-12-10 10:01:54

问题


I'm quite new to Laravel. I'm figuring out to work with Eloquent.

Let's say I have 2 tables: categories and products. These two table have a one-to-many relationship. 1 category can have many products.

I would like to return a JSON response which consists of an array of categories where each category has an array of products. It should look like this:

[
   {"name":"Category 1", "products": [
                                        {"name":"Product 1","price":"2.50"},
                                        {"name":"Product 2","price":"2.50"}
                                     ]
   },
   {"name":"Category 2", "products": [
                                        {"name":"Product 1","price":"1.95"},
                                        {"name":"Product 2","price":"2.15"}
                                     ]
   }
]

Models:

Category.php

<?php

class Category extends Eloquent{

    protected $table = 'categories';

    public function products(){
        return $this->hasMany('Product');
    }
}

Product.php

<?php

class Product extends Eloquent {

    protected $table = 'products';

    public function categories(){
        return $this->belongsTo('Category');
    }
}

Database tables:

create_categories_table:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoriesTable extends Migration {

    public function up()
    {
        Schema::create('categories', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
    }

    ...
}

create_products_table:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration {

    public function up()
    {
        Schema::create('products', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('price');
            $table->unsignedInteger('category_id');
            $table->foreign('category_id')->references('id')->on('categories');
            $table->timestamps();
        });
    }

    ...
}

Controller:

class ApiController extends BaseController {

public function getIndex(){

    $categories = Category::all();

    return Response::json(array('data' => $categories));
}

}

I know how to return all of the categories or products or only the name of a category but I cannot seem to find the solution for the example of json response I mentioned above.

If anyone knows this it would be really helpful. Thanks in advance.


回答1:


If I understood your question correctly, you could simply do this:

public function getIndex(){
    $categories = Category::with('Products')->get();
    return Response::json(array('data' => $categories));
}

The with() eager loads the relationship so you get pretty much what you want.

By the way, you'll probably want to change the name of this method

public function categories(){
    return $this->belongsTo('Category');
}

to category() instead, since every product can only belong to one category.



来源:https://stackoverflow.com/questions/24600013/how-to-return-a-json-response-based-on-database-relationship-using-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!