【问题标题】:Retrieve data from associated database in cakephp从 cakephp 中的关联数据库中检索数据
【发布时间】:2018-11-13 04:52:22
【问题描述】:

我有一个 Entries 表,其中 users_id 作为 Users 表的外键。

我在 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 中执行相同的任务?

【问题讨论】:

  • 签入你的控制器调试($entry);然后看看数据显示了什么。
  • 你也要添加你的视图方法吗?

标签: cakephp cakephp-3.0


【解决方案1】:

你可以像下面这样写

在控制器中

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 ?>

【讨论】:

  • 谢谢!问题是我的视图方法的参数不是$id,而是$title。似乎 get() 不适用于非主键的字段。
  • 谢谢 我想出了如何通过在代码中添加位来解决这个问题: $entries = TableRegistry::get('Entries'); $query = $entries->findByTitle($title); $q = $query->first(); $id = $q->id; $entry = $this->Entries->get($id, [ 'contain' => ['Users'] ]); $this->set('entry', $entry);
  • @Karim Ahh,这比我乱七八糟的代码要好得多。谢谢
【解决方案2】:

所以在 cakephp 中你正在加载它的控制器的模型,这是默认完成的,你可以直接在同一个控制器中创建一个 find() 方法,如果你想从其他表/模型中查找,你可以这样做-

一个。 $this->Entries->otherTableName()->find()->all();

b. $tableName= $this->loadModel('tableName'); $tableName->find();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2014-02-27
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多