首页 >后端开发 >php教程 >多列在Laravel收藏中拔出

多列在Laravel收藏中拔出

Karen Carpenter
Karen Carpenter原创
2025-03-06 02:38:09290浏览

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