. Tidak seperti map
, yang terhad kepada lajur tunggal, menggabungkan pluck()
dengan map
menyediakan fleksibiliti yang dipertingkatkan untuk pengekstrakan data. only
memanfaatkan
map
only
dan map
membolehkan pengekstrakan efisien pelbagai lajur yang ditentukan dari koleksi. Inilah cara melaksanakan teknik ini: only
<?php namespace App\Http\Controllers; use App\Models\Article; use Illuminate\Http\Request; class ArticleController extends Controller { public function list() { return Article::take(20)->get()->map(fn($article) => $article->only([ 'title', 'content', 'summary', 'url_path' ])); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::create('articles', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->text('summary'); $table->string('url_path'); $table->timestamps(); }); } }; // ArticleSeeder.php use App\Models\Article; use Illuminate\Database\Seeder; class ArticleSeeder extends Seeder { public function run() { Article::create([ 'title' => 'Getting Started', 'content' => 'Full article content here...', 'summary' => 'Quick guide to get started', 'url_path' => 'getting-started' ]); Article::create([ 'title' => 'Advanced Topics', 'content' => 'Advanced content here...', 'summary' => 'Deep dive into features', 'url_path' => 'advanced-topics' ]); } }
[ { "title": "Getting Started", "content": "Full article content here...", "summary": "Quick guide to get started", "url_path": "getting-started" }, { "title": "Advanced Topics", "content": "Advanced content here...", "summary": "Deep dive into features", "url_path": "advanced-topics" } ]
dan map
menawarkan kaedah ringkas dan cekap untuk memilih pelbagai lajur dari koleksi Laravel, menghasilkan kod yang lebih bersih dan lebih diselenggara. only
Atas ialah kandungan terperinci Pelbagai lajur memetik koleksi Laravel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!