Wrong data update in Laravel database operation
P粉336536706
P粉336536706 2023-08-07 20:33:01
0
1
486
<p>以下是我模型中的函数代码:</p> <pre class="brush:php;toolbar:false;">public function updateAnime(Request $request) { $updatedFields = []; $request->validate([ 'title' => ['required'], 'release_date' => ['required', 'integer'], 'author' => ['required'], 'studio' => ['required'], 'description' => ['required'], ]); $request->release_date = (int)$request->release_date; $animeInfo = Anime::where('title', $request->oldTitle)->with('authors', 'studios')->first(); $author = Author::firstOrCreate(['author' => $request->author]); AuthorAnime::where([ ['author', $animeInfo->authors[0]->author], ['anime', $request->oldTitle] ])->update([ 'author' => $author->author, 'anime' => str_replace(' ', '-', $request->title) ]); $studio = Studio::firstOrCreate(['studio_name' => $request->studio]); StudioAnime::where([ ['studio', $animeInfo->studios[0]->studio_name], ['anime', $request->oldTitle] ])->update([ 'studio' => $studio->studio_name, 'anime' => str_replace(' ', '-', $request->title) ]); foreach ($request->all() as $key => $value) { if (property_exists($animeInfo, $key)) { if ($request->$key != $animeInfo->$key) { $updatedFields[$key] = $request->$key; } } } $animeInfo->update($updatedFields); return response()->json(['message' => 'Data was updated successfully. n Updated data: ' . implode(', ', array_keys($updatedFields))]); }</pre> <p>控制器代码:</p> <pre class="brush:php;toolbar:false;">$anime = new Anime(); return $anime->updateAnime($request);</pre> <p>问题是,它更新相关的表StudioAnime和AuthorAnime,它也在表Studio和动漫中创建新的数据,但它不更新表动漫。Guys, why is this happening and how to solve it<br /><br />When in my previous code I just updated the data without checking its changes it all worked</p><p>< br /></p> <pre class="brush:php;toolbar:false;">$animeInfo->update([ 'title' => str_replace(' ', '-',$request->title), 'poster' => $animeInfo->poster, 'description' => $request->description, 'release_date' => $request->release_date, 'trailer' => $animeInfo->trailer, ]); return response()->json(['message' => 'Data was updated successuflly']);```</pre> <p><br /></p>
P粉336536706
P粉336536706

reply all(1)
P粉533898694

You cannot use the property_exist() function to obtain column names because these properties cannot be accessed directly as properties in the Model object.

To check this, try tinker:


dd(User::first())

My suggestion is to use the attributesarray() or getAttributes() method combined with array_keys() to get the attribute name array of the model. Isn’t this done:

$animeAttributes = array_keys($animeInfo->getAttributes());

foreach ($request->all() as $key => $value) {

    if (in_array($key, $animeAttributes)) {

    /* ... */
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template