首頁 >後端開發 >php教程 >多列在Laravel收藏中拔出

多列在Laravel收藏中拔出

Karen Carpenter
Karen Carpenter原創
2025-03-06 02:38:09298瀏覽

Multiple Column Plucking in Laravel Collections

Laravel提供了一種簡化的方法,可以使用

>方法從集合中檢索多個列。與僅限於單列列的map不同,將pluck()map組合為數據提取提供了增強的靈活性。 only>

使用maponly

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn