我使用这个表模式:
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'];
}
在控制器中,我想显示所有模型项的列表,但只显示 id
和 name
fileds . 现在我使用它,但它显示所有不隐藏的字段:
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()
函数中所需的字段?
2 回答
如果我没有错,那么希望你可以这样做以获得特定列和分页:
如果我正确地读了你的问题,你想要做的是创建一个
Form
对象的集合,其中只有id
和name
字段实际上在索引概述上被检索 .您可以通过在控制器中创建新的集合实例来轻松完成此操作:
我个人会将该集合放在存储库模式中,以使其更容易缓存 . Here's a nice canonical reference到Laravel中的存储库模式 .
在你的控制器上的show函数中,你不需要改变一个东西,考虑到ID仍然是相同的 .
为了将来参考,请记住,paginate方法仅对其调用的集合进行分页,而不是与特定模型或该集合以外的任何其他内容相关的所有内容 . 因此,如果您以任何方式创建新集合,并在该新集合上调用paginate方法,则只会对其中的任何内容进行分页 . 这是非常强大的东西! Here's the documentation reference.