在 find('list') 中使用多个 valueFields
Using multiple valueFields in find('list')
尝试在我的查找方法中使用多个字段 -
$users = $this->AdressesUsers->users->find('list', [
'keyField' => 'id',
'valueField' => ['firstname','lastname'],
]);
工作,有点。因为两者之间用分号隔开。也尝试过使用 mutator 方法,但这很失败。
在我的函数中
'valueField' => function ($e) {
return $e->author->get('full_name');
}
在我的实体用户中
protected function _getFullName()
{
return $this->firstname . ' ' . $this->lastname;
}
我永远不会把实体弄乱,让它没有逻辑并且尽可能简单。
此处更好的方法是使用您已经尝试过的方法:
'valueField' => function ($e) {
return $e->first_name . ' ' . $e->last_name . ' ' . $e->more;
}
等
只需 debug() 此处的实体,您将看到它包含整个数据集,您可以根据需要将它们组合在一起。
我建议您在这里使用 Queries As Collection Objects。
试试这个:
$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
你可以像普通字段一样使用虚拟字段,
$this->AdressesUsers->users->find('list', [
'keyField' => 'id',
'valueField' => function ($e) {
return $e->full_name;
}
]);
额外
你也可以 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;
}
]);
尝试在我的查找方法中使用多个字段 -
$users = $this->AdressesUsers->users->find('list', [
'keyField' => 'id',
'valueField' => ['firstname','lastname'],
]);
工作,有点。因为两者之间用分号隔开。也尝试过使用 mutator 方法,但这很失败。
在我的函数中
'valueField' => function ($e) {
return $e->author->get('full_name');
}
在我的实体用户中
protected function _getFullName()
{
return $this->firstname . ' ' . $this->lastname;
}
我永远不会把实体弄乱,让它没有逻辑并且尽可能简单。
此处更好的方法是使用您已经尝试过的方法:
'valueField' => function ($e) {
return $e->first_name . ' ' . $e->last_name . ' ' . $e->more;
}
等 只需 debug() 此处的实体,您将看到它包含整个数据集,您可以根据需要将它们组合在一起。
我建议您在这里使用 Queries As Collection Objects。 试试这个:
$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
你可以像普通字段一样使用虚拟字段,
$this->AdressesUsers->users->find('list', [
'keyField' => 'id',
'valueField' => function ($e) {
return $e->full_name;
}
]);
额外 你也可以 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;
}
]);