ホームページ >バックエンド開発 >PHPチュートリアル >Laravelコレクションで複数の列を摘み取ります
Laravelは、map
メソッドを使用してコレクションから複数の列を取得するための合理化されたアプローチを提供します。単一の列に限定されているpluck()
とは異なり、map
とonly
を組み合わせて、データ抽出の柔軟性が向上します。
レバレッジ
map
only
メソッドとmap
メソッドの相乗効果により、コレクションから複数の指定された列を効率的に抽出できます。 この手法を実装する方法は次のとおりです
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' ])); } }
API応答には、指定されたフィールドのみが含まれます。
<?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" } ]の組み合わせは、Laravelコレクションから複数の列を選択するための簡潔で効率的な方法を提供し、よりクリーンで保守可能なコードになります。
以上がLaravelコレクションで複数の列を摘み取りますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。