You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Eloquent ORM关联查询:实现Store API嵌套返回City与State数据

实现店铺数据嵌套城市及州(省)数据的解决方案

1. 完善模型关联配置

State 模型

添加与City的一对多关联:

// app/Models/State.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class State extends Model
{
    protected $fillable = ['name', 'initials'];

    public function cities(): HasMany
    {
        return $this->hasMany(Citie::class, 'states_id');
    }
}

Citie 模型

补充与State的从属关联:

// app/Models/Citie.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Citie extends Model
{
    protected $fillable = ['states_id']; // 补充你的其他字段

    // 关联所属州
    public function state(): BelongsTo
    {
        return $this->belongsTo(State::class, 'states_id');
    }

    // 已有关联:关联店铺
    public function stores(): HasMany
    {
        return $this->hasMany(Store::class, 'cities_id');
    }
}

Store 模型

确保现有关联正确(无需修改,只要关联名称匹配即可):

// app/Models/Store.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Store extends Model
{
    protected $fillable = ['cities_id']; // 补充你的其他字段

    public function city(): BelongsTo
    {
        return $this->belongsTo(Citie::class, 'cities_id');
    }
}

2. 在查询中加载嵌套关联

直接在控制器中实现

修改StoreController的index方法,使用with()嵌套加载关联:

// app/Http/Controllers/API/v1/StoreController.php
namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Store;

class StoreController extends Controller
{
    public function index()
    {
        // 嵌套加载city及city对应的state
        $stores = Store::with('city.state')->get();
        
        return response()->json($stores);
    }
}

基于Repository模式实现

如果用Repository封装查询逻辑,修改Repository方法:

// app/Repositories/StoreRepository.php
namespace App\Repositories;

use App\Models\Store;

class StoreRepository
{
    public function getAllStoresWithNestedRelations()
    {
        return Store::with('city.state')->get();
    }
}

然后在控制器中调用:

// StoreController.php
public function index(StoreRepository $storeRepo)
{
    $stores = $storeRepo->getAllStoresWithNestedRelations();
    return response()->json($stores);
}

3. 预期返回格式

此时接口localhost:8000/v1/api/store会返回嵌套完整的JSON数据:

[
    {
        "id": 1,
        "cities_id": 1,
        "other_store_field": "xxx",
        "city": {
            "id": 1,
            "states_id": 1,
            "other_city_field": "xxx",
            "state": {
                "id": 1,
                "name": "广东省",
                "initials": "GD"
            }
        }
    }
]

内容的提问来源于stack exchange,提问作者Gustavo Gomes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 01:24:29