问题
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