LaraCSV--从 Eloquent 模型中生成 CSV 文件
LaraCSV 是 Muhammad Usman 新发布的包,它允许你流畅的从 Eloquent 模型中生成csv文件。
这些代码样例是展示使用 LaraCSV 多简单。
$users = User::get(); // All users
$csvExporter = new \Laracsv\Export();
$csvExporter->build($users, ['email', 'name'])->download();
如果你执行这个方法,将会下载一个包含用户信息的csv文件,例如:
email,name
eric@example.com,"Eric L. Barnes"
john@example.com,"John Smith"
bob@example.com,"Bob Jones"
除此的基础操作之外,他也包含一些更强大的特性:
调整字段值
$csvExporter = new \Laracsv\Export();
$users = User::get();
// Register the hook before building
$csvExporter->beforeEach(function ($user) {
$user->created_at = date('f', strtotime($user->created_at));
});
$csvExporter->build($users, ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);
添加一列
// The notes field doesn't exist so values for this field will be blank by default
$csvExporter->beforeEach(function ($user) {
// Now notes field will have this value
$user->notes = 'Add your notes';
});
$csvExporter->build($users, ['email', 'notes']);
Eloquent 关联关系
这个将会获取到商品名称和关联的种类名称,一个一对一关联关系
$products = Products::with('category')->get();
$csvExporter->build($products, ['title', 'category.title']);
在 Github 上查看项目, 查看他的 readme 文档和更多例子。
可以试试这个。
翻译自:https://laravel-news.com/generate-csv-file...
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由 Summer
于 7年前 加精
做导入导出很方便了
@ADKi 哈哈,这个主要是提供了简单的导出功能
:+1:
@JokerLinly 谢谢支持啊
created_atye也是Carbon类
$user->created_at = date('f', strtotime($user->created_at));
可以$user->created_at=$user->created_at->format('f');
@mingyun 厉害啊