3

我有一个包含 json 数据的“poin”列的成员表,例如:

{"IDR":"100", "MYR":"50", "DOLLAR":"25"}

如何使用数据表在一个单元格表中显示该 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"}
            ]
        });

谢谢

4

1 回答 1

5

首先考虑将 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

您可能需要阅读文档并稍微修改一下此代码,因为我尚未对其进行测试,这只是为了指导您尝试变压器的想法。

于 2017-11-13T11:08:54.197 回答