我有一个成员表,其中包含带有json数据的'poin'列, 例如:
{“IDR”:“100”,“MYR”:“50”,“DOLLAR”:“25”}
如何使用datatable在一个单元格表中显示json数据?
Name | Poin |
____________________
User 1|IDR : 100 |
|MYR : 50 |
|DOLLAR : 25 |
____________________
User 2|IDR : 50 |
|MYR : 80 |
|DOLLAR : 125|
这是控制器
public function query(Request $request)
{
$query = DB::table('members');
$result = DataTables::of($query)->make(true);
return $result;
}
这是blade.php
var oTable = $('#datatable-responsive').DataTable({
autoWidth: false,
processing: true,
serverSide: true,
responsive: true,
ajax: {
url: "{{route('members.query')}}",
method: "POST",
data: function (d) {
d.search = $('input[type="search"]').val();
}
},
columns: [
{data: "name"},
{data: "poin"},
{data: "created_at"}
]
});
由于
答案 0 :(得分:3)
首先考虑将Member模型中的JSON字段转换为数组:
class Member extends Model
{
protected $casts = [
'poin' => 'array',
];
}
https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting
然后,您可以在创建数据表时为您的模型编写变换器,以便将JSON字段poin
输出为HTML:
namespace App\Transformers\Datatables;
use League\Fractal;
use App\Models\Member;
class MemberTransformer extends Fractal\TransformerAbstract
{
public function transform(Member $member)
{
return [
'id' => $member->id,
'name' => $member->name,
'poin' => "IDR: {$member->poin['IDR']} <br> MYR: {$member->poin['MYR']} <br> DOLLAR: {$member->poin['DOLLAR']}"
];
}
}
https://yajrabox.com/docs/laravel-datatables/master/response/fractal
然后应用变压器...
public function query(Request $request)
{
$model = Member::query();
$result = DataTables::of($model)
->setTransformer('App\Transformers\Datatables\MemberTransformer')
->toJson();
return $result;
}
https://yajrabox.com/docs/laravel-datatables/master/engine/eloquent
您可能需要阅读文档并稍微修改一下这段代码,因为我还没有对其进行测试,它只是为了引导您尝试变形金刚的想法。