我有两个表用户和主题
用户有此字段的用户名,ID,电子邮件等。 科目有这个字段数学,英语,id,user_id,
/ UsersController.php /
public function grade($id = null)
{
$users = $this->Users->get($id, [
'contain' => [
'Subjects'
]
]);
$this->set('users', $users);
$this->set('_serialize', ['user']);
//pr($users);exit;
}
/ * grade.ctp /
[![<div class="users view large-10 medium-9 columns">
<?php
//pr($users);exit;
foreach ($users as $user): ?>
<div class="row">
<div class="large-5 columns strings">
<h6 class="subheader"><?= __('Username') ?></h6>
<p><?= h($user->username) ?></p>
<p><?php echo $this->user->username;?></p>
</div>
<div class="large-2 columns numbers end">
<h6 class="subheader"><?= __('Id') ?></h6>
<p><?= $this->Number->format($user->id) ?></p>
</div>
</div>
<?php endforeach; ?>
</div>][1]][1]
当我点击视图等级数据时,将使用pr($ users)
输出App\Model\Entity\User Object
(
[username] => Tyra
[password] => 97a8afcf419cc231e1bdcd8584b0a246
[id] => 6
[email] => tyra@gmail.com
[profile_pic] => Resource id #196
[destination] =>
[created] =>
[subjects] => Array
(
[0] => App\Model\Entity\Subject Object
(
[math] => 100
[english] => 100
[history] => 100
[science] => 100
[id] => 11
[user_id] => 6
[[new]] =>
[[accessible]] => Array
(
[*] => 1
)
[[dirty]] => Array
(
)
[[original]] => Array
(
)
[[virtual]] => Array
(
)
[[errors]] => Array
(
)
[[repository]] => Subjects
)
)
[[new]] =>
[[accessible]] => Array
(
[*] => 1
)
[[dirty]] => Array
(
)
[[original]] => Array
(
)
[[virtual]] => Array
(
)
[[errors]] => Array
(
)
[[repository]] => Users
)
我尝试pr($ users);在grade.ctp视图中我得到了上面的数据,这是正确的包含主题字段。但如何在grade.ctp视图中打印
答案 0 :(得分:0)
由于您的数据是对象格式, 你可以这样做:
<?php
echo $users->username; // prints username
echo $users->email;
?>
打印主题:
<?php
if(!empty($users->subjects)) {
foreach($users->subjects as $subject) {
echo $subject->math; // prints math
echo $subject->english; // etc
}
}
?>
您可以尝试blog tutorials在一段时间内更熟悉这些......