gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:29:11 26 4
gpt4 key购买 nike

我对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com