将数据存储到不同的表中

时间:2015-10-26 11:56:22

标签: php laravel

我有2张桌子

一个是牌照

{
    "data": {
        "id": 1,
        "container_slot_id": 3,
        "created_at": "2015-10-26 08:26:32",
        "updated_at": "2015-10-26 08:26:32"
    }
}

另一个是 plate_containers

"data": {
    "id": 1,
    "name": "Mrs. Maritza Pollich DVM",
    "equipment_status_codes_id": 8,
}

这是我的控制器

 public function storePlateCleaningData(PlateCleaningRequest $request, $id)
    {
        $plate = Plate::find($id);

       $data = $request->all();

        if ($plate->update($data)) {
            return response()->json([
                'Success' => [
                    'message' => 'Plate is Cleaned!'
                ]
            ], 201);
        }
        else
        {
            return response()->json([
                'Error' => [
                    'message' => 'Plate is not updated, something went wrong!'
                ]
            ], 400);
        }


    }

我想,当用户更新plate时,他必须能够更新 plate_containers 表的equipment_status_codes_id。我怎样才能做到这一点?我可以将两个模型注入我的构造函数中,但现在是什么?

更新:表格中的关系

牌照

$table->integer('plate_container_id')->nullable()->unsigned();

    $table->foreign('plate_container_id')->references('id')->on('plate_containers')->onDelete('cascade')->onUpdate('cascade');

模型看起来像这样。

  public function plateContainer()
    {
        return $this->belongsTo('App\Models\PlateContainer');
    }

PlateContainer

public function plates()
{
    return $this->hasMany('App\Models\Plate');
}

1 个答案:

答案 0 :(得分:0)

我从你的问题中收集的是:

一块盘子属于一个盘子容器。

如果是这种情况,请尝试使用以下代码作为控制器(将xxx替换为equipment_status_codes_id

public function storePlateCleaningData(PlateCleaningRequest $request, $id)
{
    //Let's eager load Plate Container
    $plate = Plate::with('plateContainer')->find($id);

   $data = $request->all();

    if ($plate->update($data)) {

        //Check if plate has container
        if($plate->plateContainer) {
            //Update plate container's equipment_status_codes_id 
            $plate->plateContainer->equipment_status_codes_id = xxx
            $plate->plateContainer->save();
        }

        return response()->json([
            'Success' => [
                'message' => 'Plate is Cleaned!'
            ]
        ], 201);
    }
    else
    {
        return response()->json([
            'Error' => [
                'message' => 'Plate is not updated, something went wrong!'
            ]
        ], 400);
    }


}