如何使用分页获取 Laravel Eloquent 中的特定列?

How to get specific columns in Laravel Eloquent with pagination?

我使用这个 table 模式:

Schema::create('forms', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 255)->default('');
    $table->text('html')->nullable();
    $table->text('json')->nullable();

    $table->timestamps();
    $table->softDeletes();
});

这是型号:

class Form extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'name',
        'html',
        'json'
    ];

    protected $hidden = ['created_at', 'updated_at', 'deleted_at'];
}

在控制器中,我想显示模型所有项目的列表,但只显示 idname 字段。现在我使用它,但它显示所有未隐藏的字段:

public function index() {
    return Form::->paginate(100);
}

此功能仅适用于表单名称列表。但这是第二个用于显示修改的表单数据:

public function show(string $id) {
    $item = Form::findOrFail($id);

    return response()->json($item);
}

当然最后一个函数需要显示所有字段(id、name、html 和 json)。

是否有任何最佳实践可以仅显示我在与 paginate() 一起使用的 index() 函数中需要的字段?

如果我没看错你的问题,你想要做的是创建一个 Form 对象的集合,其中实际上只检索 idname 字段索引概览。

您可以通过在控制器中创建一个新的集合实例来轻松地做到这一点:

public function index() {
   // use the Eloquent select() function
   $forms = Form::select('id', 'name')->paginate(100);
   return $forms;
}

我个人会将该集合放入存储库模式中,以使其更易于缓存。 Here's a nice canonical reference 到 Laravel 中的存储库模式。

考虑到 ID 仍然相同,您无需在控制器的显示功能中进行任何更改。

为了将来参考,请记住 paginate 方法仅对调用它的集合进行分页,而不对与特定模型相关的所有内容或该集合以外的任何内容进行分页。因此,如果您以任何方式创建一个新集合,并对该新集合调用 paginate 方法,则只有其中的内容才会被分页。这是非常强大的东西! Here's the documentation reference.

如果我没记错的话,希望您可以像这样获取特定的列和分页:

return Form::paginate(100,['id','name',.....]);