首页 > 解决方案 > 在 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); 
    }

标签: phplaravellaravel-5laravel-5.6

解决方案


解决方案是在 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];
        }
    ...
}

推荐阅读