如何在Laravel 5.2中使用Yajra Datatables和Dimsav Translatable的Eager Loading

时间:2016-03-21 12:18:38

标签: datatables laravel-5.2

我正在使用yajra / laravel-datatables和dimsav / laravel-translatable来创建角色表。

数据表结构如下。 角色表迁移:

Schema::create('roles', function (Blueprint $table) {
    $table->increments('id');
    $table->softDeletes();
    $table->timestamps();
});

角色转换表迁移:

Schema::create('role_translations', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('role_id')->unsigned();
    $table->string('name')->index();
    $table->string('locale')->index();

    $table->unique(['role_id', 'name', 'locale']);
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});

现在我在控制器上这样做......

public function indexData()
{
    $roles = Role::join('role_translations', 'roles.id', '=', 'role_translations.role_id')
        ->select(['roles.id', 'role_translations.name', 'roles.created_at', 'roles.updated_at'])
        ->groupBy('roles.id');

...这在视图中(数据表初始化和常规设置在一个公共的js文件中完成,特定设置作为HTML属性传递)...

<table class="table table-striped table-bordered" data-table data-ajax="{{ url('/admin/role/index-data') }}" data-responsive="true">
    <thead>
        <tr>
            <th data-priority="1">{{ trans('messages.name') }}</th>
            <th>{{ trans('messages.created') }}</th>
            <th>{{ trans('messages.modified') }}</th>
            <th data-priority="1" data-sortable="false" data-class-name="actions">{{ trans('messages.actions') }}</th>
        </tr>
    </thead>
</table>

它可以工作,但我对在查询中加入所有这些内容感到不舒服,我想做类似的事情

$roles = Role::with('translation')->select(['roles.id', 'role_translations.name', 'roles.created_at', 'roles.updated_at'])

但我没有运气。

3 个答案:

答案 0 :(得分:0)

这是我热切加载的工作示例。我希望这可以帮到你

//控制器查询

$medicine  = Medicine::with(['manufacturer','doseageForm','measureUnit','supplier'])
            ->select(['id','product_name','generic_name','product_class','manufacturer_id', 
                      'doseage_form_id','measure_unit_id','strenght','status']);

return Datatables::of($medicine)
        ->editColumn('status', function($medicine){
            return (($medicine->status == 1)?"Active":"Deactive");
        })
        ->editColumn('manufacturer_id', function($medicine){

            $manufacturer_name   =   $medicine->manufacturer->name;
            return $manufacturer_name;
        })
        ->editColumn('product_name', function($medicine){
            return 
                $medicine->product_name.", ".
                    $medicine->doseageForm->name.", ".
                    $medicine->strenght.$medicine->measureUnit->name;
        })
        ->addColumn('supplier',function($medicine){

            if($medicine->supplier->count() > 0){
                return $medicine->supplier->first()->qualified_person;
            }else{
                return '---';
            }
        })
        ->addColumn('actions', function($medicine){

            $edit_route =   route('medicine-edit',['id'=>$medicine->id ]);
            $del_route  =   route("ajax-delete",["type"=>"medicine","id"=>$medicine->id ]);

            $status     =   (($medicine->status == 1)?
                                '<a href="" class="btn btn-xs btn-warning"><i class="fa fa-eye"></i></a>'
                                :
                                '<a href="" class="btn btn-xs btn-warning"><i class="fa fa-eye-slash"></i></a>'
                            );

            $html       =   '<div class="btn-group">
                                '.$status.'
                                <a href="'.$edit_route.'" class="btn btn-xs btn-primary" alt="edit"><i class="fa fa-pencil"></i></a>
                                <a href="'.$del_route.'" data-target="#ajax_delete" alt="delete" data-toggle="modal" class="btn btn-xs btn-danger">
                                    <i class="fa fa-trash-o"></i>
                                </a>
                            </div>';

            return $html;
        })
        ->make(true);

我的观看代码是

<table class="table table-bordered table-striped table-condensed flip-content" id="medicine">
    <thead class="flip-content">
        <tr>
            <th>Medicine</th>
            <th>Generic</th>
            <th>Class</th>
            <th>Manufacturer</th>
            <th>Supplier</th>
            <th>Actions</th>
        </tr>
    </thead>
</table>

我的数据表的JS脚本

<script type="text/javascript">
    var oTable;

    $(document).ready(function() {
        oTable = $('#medicine').DataTable({
            "responsive": true,
            "processing": true,
            "serverSide": true,
            "ajax": "{!!route('medicine-data')!!}",
            "columns": [
                {data: 'product_name',       name: 'product_name'},
                {data: 'generic_name',       name: 'generic_name'},
                {data: 'product_class',       name: 'product_class'},
                {data: 'manufacturer_id',         name: 'manufacturer_id'},
                {data: 'supplier',           name: 'supplier'},
                {data: 'actions',            name: 'actions'},
            ]
        });                        
    });
</script>

答案 1 :(得分:0)

在角色模型中创建关系方法
public function translation(){ return $this->hasMany("\App\Translation"); }

然后在你的RoleController中查询 $roles = Role::with('translation')->get();

此外,您还可以在翻译中添加条件 $roles = Role::with('translation',function($query){ return $query->where('locale','en'); })->get();

或按照此Laravel文档https://laravel.com/docs/5.2/eloquent-relationships

答案 2 :(得分:0)

也许可以通过在with()中传递闭包函数来完成。

请参阅此回答https://stackoverflow.com/a/19921418/1061663