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

多列在Laravel收藏中拔出

Karen Carpenter
发布: 2025-03-06 02:38:09
原创
288 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板