find(list) returns several blank options, find(all) returns correct data but formatted with {

时光毁灭记忆、已成空白 提交于 2019-12-02 18:48:25

问题


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

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