在列表显示名称,而不是id

1.app/common.php底部

function addtion($items, $fields)
{
    if(!$items)
        return $items;
    $fieldsArr = [];
    if (!is_array($fields))
    {
        $arr = explode(',', $fields);
        foreach ($arr as $k => $v)
        {
            $fieldsArr[$v] = ['field' => $v];
        }
    }
    else
    {
        foreach ($fields as $k => $v)
        {
            if (is_array($v))
            {
                $v['field'] = isset($v['field']) ? $v['field'] : $k;
            }
            else
            {
                $v = ['field' => $v];
            }
            $fieldsArr[$v['field']] = $v;
        }
    }
    foreach ($fieldsArr as $k => &$v)
    {
        $v = is_array($v) ? $v : ['field' => $v];
        $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
        $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
        $v['column'] = isset($v['column']) ? $v['column'] : 'name';
        $v['model'] = isset($v['model']) ? $v['model'] : '';
        $v['table'] = isset($v['table']) ? $v['table'] : '';
        $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
    }
    unset($v);
    $ids = [];
    $fields = array_keys($fieldsArr);
    foreach ($items as $k => $v)
    {
        foreach ($fields as $m => $n)
        {
            if (isset($v[$n]))
            {
                $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
            }
        }
    }
    $result = [];
    foreach ($fieldsArr as $k => $v)
    {
        if ($v['model'])
        {
            $model = new $v['model'];
        }
        else
        {
            $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
        }
        $primary = $v['primary'] ? $v['primary'] : $model->getPk();
        $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
    }
    foreach ($items as $k => &$v)
    {
        foreach ($fields as $m => $n)
        {
            if (isset($v[$n]))
            {
                $curr = array_flip(explode(',', $v[$n]));
                $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
            }
        }
    }
    return $items;
}
  1. 在你想要的控制器加
$list = addtion($list, 'host_ids');

3.对应js(这个不可以搜索)

{field: 'host_names', title: __('Host_id'), operate: false, formatter: Table.api.formatter.label},

如图我只关联一个:
https://cdn.forum.fastadmin.net/uploads/201709/28/ed812d47f877c7837804bcc23499a3bc

24 条评论

发布
问题