【问题标题】:Laravel Datatables Sorting Appended FieldsLaravel 数据表对附加字段进行排序
【发布时间】:2016-05-20 11:17:13
【问题描述】:

我的模型ItemsRooms相关,BuildingsLocations相关。

短:ItemsbelongsTo RoomsbelongsTo BuildingsbelongsTo Locations

ItemController的索引函数中,我想显示一个Items的表格。我使用 Laravel 数据表。它适用于“简单”表,但我遇到了排序/搜索自定义/附加字段的问题,因为它们当然不在表中。

基本上我想在显示表中为每个Item 加入RoomBuildingLocation 名称。

这是我的Items 模特:

protected $appends = [
    'building_title',
    'location_title',
    'room_title',
];

public function getLocationTitleAttribute() {
    return $this->room->building->location->title;
}

public function getBuildingTitleAttribute() {
    return $this->room->building->title;
}

public function getRoomTitleAttribute() {
    return $this->room->title;
}

这是我的控制器:

public function anyData()
{
    return Datatables::of(Item::query())->make(true);
}

为附加字段启用排序/过滤的最佳方法是什么? 感谢您的阅读。

【问题讨论】:

    标签: php mysql laravel datatables eloquent


    【解决方案1】:

    这是我的解决方案(没有使用附加字段):

    public function anyData()
    {
        $items = Item::join('rooms', 'items.room_id', '=', 'rooms.id')
            ->join('buildings', 'rooms.building_id', '=', 'buildings.id')
            ->join('locations', 'buildings.location_id', '=', 'locations.id')
            ->select([
                'items.id',
                'items.title',
                'items.label_number',
                'items.fibu_number',
                'rooms.title as room_title',
                'buildings.title as building_title',
                'locations.title as location_title'
            ]);
        return Datatables::of($items)->make(true);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多