首页 文章

Laravel数据表对附加字段进行排序

提问于
浏览
1

我的模型 ItemsRooms 有关,它与 Buildings 有关,它与 Locations 有关 .

简短: Items belongsTo Rooms belongsTo Buildings belongsTo Locations

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

基本上我想在显示表中为每个 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);
}

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

1 回答

  • 0

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

    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);
    }
    

相关问题