Laravel 10如何通过Model关联3张表查询并返回指定JSON?
Laravel 10 关联查询并返回指定JSON格式解决方案
1. 确认数据表结构与模型关联
假设你的三张表结构如下:
hangszerek(主表):h_id(主键)、hangszer_nev、brutto_ar、kep_url、cikkszam、leirasinstrument_types(类型表):t_id(主键)、tipus_nevhangszer_instrument_type(中间关联表):h_id、t_id(分别关联两张主表的主键)
定义Hangszer模型关联
在app/Models/Hangszer.php中添加多对多关联方法:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Hangszer extends Model { protected $table = 'hangszerek'; protected $primaryKey = 'h_id'; public $timestamps = false; // 若表无时间戳字段则添加 protected $fillable = ['hangszer_nev', 'brutto_ar', 'kep_url', 'cikkszam', 'leiras']; public function tipusok(): BelongsToMany { return $this->belongsToMany( InstrumentType::class, 'hangszer_instrument_type', // 中间表名 'h_id', // 当前模型在中间表的外键 't_id' // 关联模型在中间表的外键 )->select('t_id', 'tipus_nev'); // 指定关联数据返回字段 } }
定义InstrumentType模型
在app/Models/InstrumentType.php中配置基础属性:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class InstrumentType extends Model { protected $table = 'instrument_types'; protected $primaryKey = 't_id'; public $timestamps = false; protected $fillable = ['tipus_nev']; }
2. 控制器中查询并返回指定格式JSON
在控制器方法中使用with()预加载关联数据,同时指定主表返回字段:
<?php namespace App\Http\Controllers; use App\Models\Hangszer; use Illuminate\Http\JsonResponse; class HangszerController extends Controller { public function index(): JsonResponse { $hangszerek = Hangszer::with('tipusok') ->select('h_id', 'hangszer_nev', 'brutto_ar', 'kep_url', 'cikkszam', 'leiras') ->get(); return response()->json($hangszerek); } }
3. 验证结果
此时接口返回的JSON格式将与你期望的完全一致:
[ { "h_id": 1, "hangszer_nev": "Gitár", "brutto_ar": 100000, "kep_url": "https://image.com/image1.png", "cikkszam": "4792146AG", "leiras": "Nagyon fain gitár", "tipusok":[ {"t_id":1,"tipus_nev":"Type 1"}, {"t_id":2,"tipus_nev":"Type 2"} ] }, { "h_id": 2, "hangszer_nev": "Dob", "brutto_ar": 120000, "kep_url": "https://image.com/image2.png", "cikkszam": "47924636BF", "leiras": "Nagyon fain dob", "tipusok":[ {"t_id":2,"tipus_nev":"Type 2"}, {"t_id":3,"tipus_nev":"Type 3"} ] } ]
内容的提问来源于stack exchange,提问作者web216
相关产品推荐
相关产品推荐

