Laravel 更新事件(观察者):SQLSTATE[22001] 错误

Laravel Updated Event (Observer): SQLSTATE[22001] Error

我试图在通过 observer 进行 更新 时将 species' ID 附加到其名称,但出于某种原因它有点 looped 因此 SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 错误:

SpeciesController@update

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Species  $species
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Species $species)
    {
        $species->name = $request->name;
        $species->sort = $request->sort;

        $species->save();

        $updatedSpecies = new SpeciesResource($species);

        return response()->json(compact('updatedSpecies'), 200);
    }

SpeciesObserver@updated

    /**
     * Handle the species "updated" event.
     *
     * @param  \App\Species  $species
     * @return void
     */
    public function updated(Species $species)
    {
        $species->name = "$species->name - $species->id";

        $species->save();
    }

updated 事件总是被触发,因为您也将它保存在里面。请改用 updating 事件。

/**
 * Handle the species "updating" event.
 *
 * @param  \App\Species  $species
 * @return void
 */
public function updating(Species $species)
{
    $species->name = "$species->name - $species->id";
}