php - 在 laravel 中,许多关系数据在创建后不会直接显示/获取
问题描述
我有一个存储方法,它可以保存或更新建议文件的成人详细信息。
关系:
An AdviceFile hasMany Adult
An Adult belongsTo an AdviceFile
我认为我的方法很简单(可能是错误的),但最后当我尝试获取adults
属于adviceFile
它时它不会获取任何内容。
知道为什么会发生这种情况吗?
这是我的store
方法
public function store(AdviceFile $adviceFile, AdultDataRequest $request)
{
$requestData = $request->data;
foreach ($requestData as $adultDetails) {
if (isset($adultDetails["id"])) {
// Update the record
$keysToExclude = [
'id', 'advice_file_id', 'created_at', 'updated_at', 'deleted_at'
];
$data = array_except($adultDetails, $keysToExclude);
$adult = Adult::find($adultDetails["id"]);
$adult->data = $data;
$adult->save();
} else {
// Create record
Adult::create([
'advice_file_id' => $adviceFile->id,
'data' => $adultDetails
]);
}
}
//This is where I get an empty response, even though there is data in db
return AdultResource::collection($adviceFile->adults);
}
解决方案
解决方案是在 return 语句之前加载关系:
$adults = $adviceFile->adults()->get();
return AdultResource::collection($adults);
来自@brunodevel 和@hailwood 的学分larachat
// Illuminate\Database\Eloquent\Concerns\HasAttributes
public function getRelationValue($key)
{
// If the key already exists in the relationships array, it just means the
// relationship has already been loaded, so we'll just return it out of
// here because there is no need to query within the relations twice.
if ($this->relationLoaded($key)) {
return $this->relations[$key];
}
...
}
推荐阅读
- javascript - 无法在使用根目录的相对路径创建反应应用程序中插入自定义脚本
- distributed - 在 ifps 专用网络中上传文件时通知其他节点
- c - struct 数组指针作为函数参数
- visual-studio-code - 热门更改更漂亮的 html 标签格式
- apache-spark - spark是否将源数据、输入数据和结果表数据保留在内存中,直到流式传输时程序终止
- flutter - PageView 上 Stack 外的 BackdropFilter 覆盖
- python - 'FrameProcessor' object is not callable
- xctest - FBSnapshotTestcase 与 xcuiscreenshot
- excel - MS Access 365,图表,散点图
- react-native - ReferenceError:找不到变量:堆栈