Falsche Datenaktualisierung im Laravel-Datenbankbetrieb
P粉336536706
2023-08-07 20:33:01
<p>以下是我模型中的函数代码:</p>
<pre class="brush:php;toolbar:false;">public function updateAnime(Request $request)
{
$updatedFields = [];
$request->validate([
'title' => ['erforderlich'],
'release_date' => ['erforderlich', 'Ganzzahl'],
'Autor' => ['erforderlich'],
'studio' => ['erforderlich'],
'Beschreibung' => ['erforderlich'],
]);
$request->release_date = (int)$request->release_date;
$animeInfo = Anime::where('title', $request->oldTitle)->with('authors', 'studios')->first();
$author = Author::firstOrCreate(['author' => $request->author]);
AutorAnime::where([
['Autor', $animeInfo->authors[0]->author],
['anime', $request->oldTitle]
])->update([
'Autor' => $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' => 'Daten wurden erfolgreich aktualisiert. n Aktualisierte Daten: ' . implode(', ', array_keys($updatedFields))]);
}</pre>
<p>控制器代码:</p>
<pre class="brush:php;toolbar:false;">$anime = new Anime();
return $anime->updateAnime($request);</pre>
<p>Leute, warum passiert das und wie kann man es lösen? /></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' => 'Daten wurden erfolgreich aktualisiert']);```</pre>
<p><br /></p>
不能用property_exist()函数获取列名,因为这些属性不能作为Model对象中的属性直接访问。
要检查这个,试试在tinker:
我的建议是,用attributesarray()或getAttributes()方法与array_keys()结合,获得模型的属性名称数组,这不就搞定了吗: