他のテーブルを呼び出す TableRegistry、
Controllerの場合はloadModel()を使おう
-2017年07月13日-
cakephpcake
【CakePHP3】無関係な複数テーブルのデータを一つのコントローラで扱う
<任意のテーブル名複数形>controll.php
use App\Controller\AppController;
use Cake\ORM\TableRegistry; //これを追記
class PersonsController extends AppController
{
public function initialize()
{
parent::initialize();
$this->tags = TableRegistry::get('tags');
}
public function index()
{
$persons = $this->paginate($this->Persons);
$this->set(compact('persons'));
$tags = $this->tags->find();
$this->set(compact('tags'));
//こんな書き方もできる
//$this->set('tags', $this->tags->find()->limit(10));
$this->loadModel('Keywords');
$keywords = $this->Keywords->find();
$this->set(compact('keywords'));
}
}
表示させたいctpで出力させます
<?php
use Cake\Routing\Router;
foreach ($tags as $tag) {
echo '<h3><a href="'.Router::url(['controller' => 'tags', 'action' => 'view', $tag->id]).'">'.$tag->title.'</a></h3>';
echo '<br>';
}
?>
<?php
foreach ($keywords as $keyword) {
echo '<h5><a href="'.Router::url(['controller' => 'keywords', 'action' => 'view', $keyword->id]).'">'.$keyword->title.'</a></h5>';
echo '<br>';
}
?>