>方法从集合中检索多个列。与仅限于单列列的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 Collections中选择多个列,从而产生更清洁,更可维护的代码。
以上是多列在Laravel收藏中拔出的详细内容。更多信息请关注PHP中文网其他相关文章!