如何使用eloquent基于数据库关系返回json响应

时间:2014-07-06 20:24:42

标签: json laravel eloquent one-to-many foreign-key-relationship

我对Laravel很新。我正在想与Eloquent合作。

假设我有2个表:类别和产品。这两个表有一对多的关系。 1类可以有很多产品。

我想返回一个JSON响应,该响应由一系列类别组成,其中每个类别都有一系列产品。它应该是这样的:

[
   {"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"}
                                     ]
   }
]

型号:

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');
    }
}

数据库表:

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();
        });
    }

    ...
}

控制器:

类ApiController扩展了BaseController {

public function getIndex(){

    $categories = Category::all();

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

}

我知道如何返回所有类别或产品或仅返回类别的名称,但我似乎无法找到上面提到的json响应示例的解决方案。

如果有人知道这将是非常有帮助的。提前谢谢。

1 个答案:

答案 0 :(得分:10)

如果我理解你的问题,你可以这样做:

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

with()渴望加载关系,这样你就能得到你想要的东西。

顺便说一下,您可能想要更改此方法的名称

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

改为category(),因为每个产品只能属于一个类别。