Heim >Backend-Entwicklung >PHP-Tutorial >Arbeiten mit JSON -Attributen mit Laravels Array -Casts
Laravel liefert AsarrayObject- und Ascollection -Abgüsse, um komplexe JSON -Attribute effektiver zu verarbeiten, um eine intuitive Manipulation verschachtelter Datenstrukturen zu ermöglichen.
<!-- Syntax highlighted by torchlight.dev --><?php use Illuminate\Database\Eloquent\Casts\AsArrayObject; use Illuminate\Database\Eloquent\Casts\AsCollection; class User extends Model { protected $casts = [ 'settings' => AsArrayObject::class, 'tags' => AsCollection::class ]; }
Lassen Sie uns ein vollständiges Beispiel eines Produktmodells untersuchen, das JSON -Attribute verwendet, um Spezifikationen und Varianten zu verwalten:
<!-- Syntax highlighted by torchlight.dev --><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Casts\AsArrayObject; use Illuminate\Database\Eloquent\Casts\AsCollection; class Product extends Model { protected $fillable = ['name', 'specs', 'variants']; protected $casts = [ 'specs' => AsArrayObject::class, 'variants' => AsCollection::class, ]; } // Migration for this model would look like: public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->json('specs'); $table->json('variants'); $table->timestamps(); }); } // Usage example: $product = Product::create([ 'name' => 'Gaming Laptop', 'specs' => [ 'processor' => 'Intel i7', 'ram' => '16GB', 'storage' => [ 'primary' => '512GB SSD', 'secondary' => '1TB HDD' ] ], 'variants' => [ ['color' => 'Black', 'price' => 999], ['color' => 'Silver', 'price' => 1099] ] ]); // // Update nested specs without any PHP errors $product->specs['storage']['primary'] = '1TB SSD'; $product->save(); // Use collection methods on variants $product->variants->push(['color' => 'Red', 'price' => 1199]); $product->save(); // Filter variants using collection methods $expensiveVariants = $product->variants->where('price', '>', 1000);
Diese Abgüsse ermöglichen eine nahtlose Manipulation von JSON -Daten gleichzeitig bei der Aufrechterhaltung eines sauberen, gewartbaren Codes. AsarrayObject bietet Array-ähnlichen Zugriff, während Ascollection die leistungsstarken Sammelmethoden von Laravel bietet.
Das obige ist der detaillierte Inhalt vonArbeiten mit JSON -Attributen mit Laravels Array -Casts. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!