问题
AvadiariesTable.php
$this->belongsTo('AlumnesGrups', [
'foreignKey' => 'alumnes_grup_id',
'joinType' => 'INNER'
AlumnesGrupsTable.php
$this->belongsTo('Alumnes', [
'foreignKey' => 'alumne_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Grups', [
'foreignKey' => 'grup_id',
'joinType' => 'INNER'
]);
Why is this in AvadiariesController.php:
public function add()
{
$avadiary = $this->Avadiaries->newEntity();
if ($this->request->is('post')) {
$avadiary = $this->Avadiaries->patchEntity($avadiary, $this->request->data);
$avadiary->user_id = $this->Auth->user('id');
if ($this->Avadiaries->save($avadiary)) {
$this->Flash->success(__('The avadiary has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The avadiary could not be saved. Please, try again.'));
}
}
$alumnesGrups = $this->Avadiaries->AlumnesGrups->find('all', [
'fields' => ['Alumnes.name'],
'contain' =>['Alumnes', 'Grups'],
'conditions' => ['Grups.id =' => 1],
'order' => ['Alumnes.name' => 'ASC']
]);
$this->set(compact('avadiary', 'alumnesGrups'));
$this->set('_serialize', ['avadiary']);
}
returning correct data but formatted like this:
{"Alumnes":{"name":"Angela Smith"}}?
How can I just get Angela Smith? If I change find(all) to find(list), the selectbox is populated with several blank options.
Thank you!
回答1:
Use find('list')
and use valueField
for the field you want to show and keyField
for its value:
$alumnesGrups = $this->Avadiaries->AlumnesGrups->find('list', [
'keyField' => 'alumne.name',
'valueField' => 'alumne.name'])
->contain(['Alumnes', 'Grups'])
->where(['Grups.id =' => 1])
->order(['Alumnes.name' => 'ASC']);
Check: http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#finding-key-value-pairs
来源:https://stackoverflow.com/questions/38514917/findlist-returns-several-blank-options-findall-returns-correct-data-but-for