Using multiple valueFields in find('list')

后端 未结 3 544
无人共我
无人共我 2021-01-29 01:24

Trying to use multiple fields in my find method -

$users = $this->AdressesUsers->users->find(\'list\', [
            \'keyField\' => \'id\',
                 


        
相关标签:
3条回答
  • 2021-01-29 02:18

    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;
        }
    ]);
    
    0 讨论(0)
  • 2021-01-29 02:21

    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
    
    0 讨论(0)
  • 2021-01-29 02:22

    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.

    0 讨论(0)
提交回复
热议问题