0
我在CakePHP 3的官方文檔之後關聯了兩個模型,並且無法在視圖(模板)中返回其中一個模型的值。CakePHP 3 - 模型之間的關係
驗證碼:
工作 - 實體
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Work extends Entity
{
protected $_accessible = [
'project' => true,
'client' => true,
'filter' => true,
'tech_1' => true,
'tech_2' => true,
'tech_3' => true,
'tech_4' => true,
'job' => true,
'status' => true,
'link' => true,
];
}
WorksImage - 實體
namespace App\Model\Entity;
use Cake\ORM\Entity;
class WorksImage extends Entity
{
protected $_accessible = [
'photo' => true,
'photo_dir' => true,
'work_id' => true,
'work' => true,
];
}
PagesController - 控制器:
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
class PagesController extends AppController
{
public function portfolio()
{
$this->loadModel('Works');
$this->loadModel('WorksImages');
$works = $this->Works->find('all',['contain' => ['WorksImages'],'limit' => 10, 'order' => ['Works.created' => 'DESC']]);
$this->set(compact('works'));
}
}
WorksTable - 表:
namespace App\Model\Table;
use App\Model\Entity\Work;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class WorksTable extends Table
{
public function initialize(array $config)
{
$this->table('works');
$this->displayField('project');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasOne('WorksImages', [
'foreignKey' => 'work_id'
]);
}
WorksImagesTable - 表
namespace App\Model\Table;
use App\Model\Entity\WorksImage;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class WorksImagesTable extends Table
{
public function initialize(array $config)
{
$this->table('works_images');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Works', [
'foreignKey' => 'work_id',
'joinType' => 'INNER'
]);
}
組合 - 視圖(模板)
<div class="container">
<div class="span12">
<h1>Portfólio</h1>
<div>
<?php foreach ($works as $work): ?>
<div>
<p><?= 'Conteúdo da tabela Works = ' . $work->project ?></p>
<p><?= 'Conteúdo da tabela WorksImages = ' . $work->work_id ?></p>
</div>
<?php endforeach ?>
</div>
</div>
</div>
我無法從WorksImagesTable模型中返回任何值。在調試期間,我意識到這些表格是相關的,此外,在視圖中,蛋糕沒有返回錯誤。
我不明白什麼是錯的。
我事先感謝任何幫助。
謝謝。
什麼是做'調試($工作 - > works_image)'的結果呢? –
你想要返回什麼?如果我正在模板上閱讀你的代碼。
<?='Conteúdoda tabela WorksImages ='。 $ work-> work_id?>
您想返回作品的圖像嗎? –