コントローラに配列を保存し、cakephpのビューファイルで使用する方法
質問
Usersコントローラーで、「Forms」テーブルにクエリを実行してユーザーが作成したフォームの数を見つけて配列に保存します。ただし、ビューファイルで配列変数を使用する方法。
通常、set関数を使用してコントローラーに変数を設定し、ビューファイルで変数を使用します。しかし、コントローラーに配列を設定する方法は?コントローラーで値を取得しました(エコーしました)。
コントローラーコード:
function users(){
$this->set('users',$this->User->find('all'));
$users=$this->User->find('all');
foreach($users as $user):
$id=$user['User']['id'];
$userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
$userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
echo "users : ".$id." ".$userFormCount[$id];
endforeach;
}
マイビューファイル:
<?php foreach($users as $user):?>
<tr>
<td class="people_profile">
<a href="/users/angeline"><?php echo $user['User']['name'];?></a>
</td>
<td>
<?php
$id=$user['User']['id'];
echo $userFormCount[$id]." ";?>forms, //need the array value here.
0 reports,
0 badges
</td>
</tr>
<?php endforeach;?>
コントローラーの変数$ userFormCountに値を保存しているため、ビューファイルに値を取得しません。しかし、配列値を設定および取得する方法は?
解決
まず、関数呼び出しの繰り返しを避ける必要があります。
関数の最初の2行は次のように置き換えることができます:
$users=$this->User->find('all');
$this->set('users', $users);
次に、オブジェクトを変更してから、オブジェクトを表示に渡し、計算するプロパティをそのオブジェクトに追加できます。
function users(){
$users=$this->User->find('all');
// notice the & here
foreach($users as & $user):
// you are repeating the same line here as well, that's not necessary
$user['User']['custom_field'] = $this->Form->find('count',
array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
endforeach;
$this->set('users', $users);
}
それから、データベースから取得する他のフィールドのようにビューで使用できます。さらに改善するには、少なくともこのカスタム値を複数回使用する場合は、このコードを User
モデルの afterFind
コールバックに移動することを検討してください。
他のヒント
配列値の設定方法はすでに知っています:-)
このコードでは、配列「users」を設定しています
$this->set('users',$this->User->find('all'));
したがって、他の配列についても同じことができます:
$this->set('userFormCount',$userFormCount);
...ユーザー変数と同じ方法で読みます。
しかし、RaYellの答えを見てください。現在のコードを改善する方法が説明されているからです。
所属していません StackOverflow