[英]How to get all models of a table with one hasMany relationship to json in Laravel 8?
目標
獲取json格式的所有具有一定hasMany關系的所有模型數據。 我想,你也可以說:在 json 中包含 hasMany 關系數據的集合。
我有兩個表: template
和template_field
以及兩個模型。
第一個 Model
class Template extends Model
{
use HasFactory;
/**
* @return HasMany
*/
public function templateField(): HasMany
{
return $this->hasMany(TemplateField::class);
}
}
第二 Model
class TemplateField extends Model
{
use HasFactory;
/**
* @return BelongsTo
*/
public function template(): BelongsTo
{
return $this->belongsTo(Template::class);
}
}
我能做的是: Template::all()->toJson()
。 但隨后 templateField 數據丟失。
編輯
這行得通。
$collection = Template::with('templateField')->get();
$collection->toJson();
$collection = Template::with('templateField')->get();
return response()->json([
'status' => true,
'data' => $collection
], 200);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.