>方法從集合中檢索多個列。與僅限於單列列的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收藏中拔出的詳細內容。更多資訊請關注PHP中文網其他相關文章!