保存模型并返回其关系

时间:2020-06-19 16:05:53

标签: php laravel eloquent polymorphism

在我的代码库中,我有一个Asset模型和一个Technology模型,

资产模型是可变形的,

public function assetable() {
    return $this->morphToMany();
}

技术模型也与之相关,

public function asset() {
    return $this->morphOne(Asset::class, 'assetable');
}

在我的控制器中,我正在执行以下操作

public function create(Request $request) {

    //Do validation

    \DB::beginTransaction();

    try {
        $technology = Technology::create([
            'technology' => $request->name,
            'type' => 'payment'
        ]);
    } catch(\Exception $e) {
        \DB::rollback();
        throw($e);
    }

    try {
        //update the already uploaded asset so it relates to the newly created Technology
        $assets = Asset::whereIn('id', $request->uploadedFile)->update([
            'assetable_id' => $technology->id,
            'assetable_type' => 'App\Payment'
        ]);
    } catch(\Exception $e) {
        \DB::rollback();
        throw($e);
    }

    \DB::commit();
    return response(['technology' => $technology->load('asset')], 201);
}

我要返回带有资产关系的新创建的技术资产作为结果的一部分,但它返回为空,

我在做什么错?当然我不需要查询数据库了吗?

1 个答案:

答案 0 :(得分:0)

在Model Technology.php中建立关系

public function asset(){
   $this->hasMany(Asset::class)
}

并在Model Asset.php中建立关系

public function technology(){
   $this->belongsTo(Technology::class)
}

在控制器中

public function create(Request $request) {

    //Do validation

    \DB::beginTransaction();

    try {
        $technology = Technology::create([
            'technology' => $request->name,
            'type' => 'payment'
        ]);

        //update the already uploaded asset so it relates to the newly created Technology
        $assets = Asset::whereIn('id', $request->uploadedFile)->update([
            'assetable_id' => $technology->id,
            'assetable_type' => 'App\Payment'
        ]);

    } catch(\Exception $e) {
        \DB::rollback();
        throw($e);
    }

    \DB::commit();
    return response(['technology' => $technology->asset], 201);
}