从 cakephp 中的关联数据库中检索数据
Retrieve data from associated database in cakephp
我有一个 Entries table users_id 作为 Users [=33] 的外键=].
我在 EntriesTable 中设置了 belongsTo 关联,如下所示:
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
之后我在 EntriesController 中写了这个:
$entries = TableRegistry::get('Entries');
$query = $entries->findByTitle($title)
->contain(['Users']);
$entry = $query->first();
$this->set('entry', $entry);
在条目的 VIEW 模板中,我必须显示编写条目的用户的 用户名 字段。
我知道在以前的 CakePHP 1 版本中,我可以只写 $entry['User']['username'] 来检索用户名写条目的用户。现在我正在使用 CakePHP 3.6,它似乎不起作用。我如何在 CakePHP 3 中执行相同的任务?
你可以这样写
在控制器中
public function view($title)
{
$entry = $this->Entries->findByTitle($title)->contain(['Users']);
$entry = $entry->first();
$this->set('entry', $entry);
}
或
public function view($title)
{
$query = $this->Entries->find('all', [
'where' => ['Entries.title' => $title],
'contain' => ['Users']
]);
$entry = $query->first();
$this->set('entry', $entry);
}
可见
<?= $entry->user->username ?>
所以在 cakephp 中你正在加载它的控制器的模型,这是默认完成的,你可以直接在同一个控制器中创建一个 find() 方法,如果你想从其他 table/ 模型中找到你可以做的是-
一个。 $this->Entries->otherTableName()->find()->all();
b。 $table名称= $this->loadModel('tableName');
$table名称->查找();
我有一个 Entries table users_id 作为 Users [=33] 的外键=].
我在 EntriesTable 中设置了 belongsTo 关联,如下所示:
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
之后我在 EntriesController 中写了这个:
$entries = TableRegistry::get('Entries');
$query = $entries->findByTitle($title)
->contain(['Users']);
$entry = $query->first();
$this->set('entry', $entry);
在条目的 VIEW 模板中,我必须显示编写条目的用户的 用户名 字段。
我知道在以前的 CakePHP 1 版本中,我可以只写 $entry['User']['username'] 来检索用户名写条目的用户。现在我正在使用 CakePHP 3.6,它似乎不起作用。我如何在 CakePHP 3 中执行相同的任务?
你可以这样写
在控制器中
public function view($title)
{
$entry = $this->Entries->findByTitle($title)->contain(['Users']);
$entry = $entry->first();
$this->set('entry', $entry);
}
或
public function view($title)
{
$query = $this->Entries->find('all', [
'where' => ['Entries.title' => $title],
'contain' => ['Users']
]);
$entry = $query->first();
$this->set('entry', $entry);
}
可见
<?= $entry->user->username ?>
所以在 cakephp 中你正在加载它的控制器的模型,这是默认完成的,你可以直接在同一个控制器中创建一个 find() 方法,如果你想从其他 table/ 模型中找到你可以做的是-
一个。 $this->Entries->otherTableName()->find()->all();
b。 $table名称= $this->loadModel('tableName'); $table名称->查找();