json - 如何使用 eloquent 根据数据库关系返回 json 响应

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

产品.php

<?php

class Product extends Eloquent {

    protected $table = 'products';

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

数据库表:

创建类别表:

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

    ...
}

创建产品表:

<?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 :

类 ApiController 扩展 BaseController {

public function getIndex(){

    $categories = Category::all();

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

}

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

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

最佳答案

如果我正确理解了您的问题,您可以这样做:

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

with() 急切地加载关系,所以你得到几乎你想要的。

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

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

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

关于json - 如何使用 eloquent 根据数据库关系返回 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600013/

相关文章:

java - 使用不同的类将 JSON 数据与 GSON 映射

javascript - 将 eval() 转换为 JSON.parse

java - 将 Map<List<Long>,List<Long>> 转换为字符串并返回

php - 在 Laravel MongoDB 中显示 EmbedsMany 数据

php - 如何在 Laravel 路由中返回一个 .xml 文件

php - laravel 查询生成器中的 SUBSTR 返回错误

mysql - 如何从数据透视表中获取给定日期范围内的最后一个条目

javascript - 以更短的方式调用 JSON 对象内部类的成员函数

php - Connection.php 第 651 行中的 Laravel QueryException : SQLSTATE[42S02]: Base table or view not found

php - 有没有办法在 laravel 5 中批量分配关系?