Using multiple valueFields in find('list')

只谈情不闲聊 提交于 2019-12-02 16:50:22

问题


Trying to use multiple fields in my find method -

$users = $this->AdressesUsers->users->find('list', [
            'keyField' => 'id',
            'valueField' => ['firstname','lastname'],            
        ]);

Works, kinda. Because the two get seperated by a semicolon. Also tried using a mutator method, but this failed badly.

In my Function

'valueField' => function ($e) {
        return $e->author->get('full_name');
    }

In my Entity User

protected function _getFullName()
    {
        return $this->firstname . '  ' . $this->lastname;
    }

回答1:


I would never mess with the entity, keep it without logic and as simple as possible.

A better approach here is to use what you already tried:

'valueField' => function ($e) {
    return $e->first_name . ' ' . $e->last_name . ' ' . $e->more;
}

etc Just debug() the entity here and you will see that it contains the whole data set and you can put it together however you like.




回答2:


I'd suggest you to use Queries As Collection Objects here. Try this:

$users = $this->AdressesUsers->Users->find()
              ->map(function ($row) { // map() is a collection method, it executes the query
                  $row->fullName = $row->firstname . ' ' . $row->lastname;
                  return $row;
               })
               ->combine('id', 'fullName') // combine() is another collection method
               ->toArray(); // Also a collections library method

pr($users);  // Check your result



回答3:


you can use virtual field just like normal field,

$this->AdressesUsers->users->find('list', [
    'keyField' => 'id',
    'valueField' => function ($e) {
           return $e->full_name;
    }
]);

Additional you can also return array in valueField,

$this->AdressesUsers->users->find('list', [
    'keyField' => 'id',
    'valueField' => function ($e) {
        $d=[];
        $d['firstname'] = $e->firstname;
        $d['lastname'] = $e->lastname;
        return $d;
    }
]);


来源:https://stackoverflow.com/questions/39905132/using-multiple-valuefields-in-findlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!