cakephp3.0 query Builder检索数据

时间:2015-03-31 10:03:50

标签: query-builder cakephp-3.0

嘿我正面临一些问题我正在尝试创建一个patientcontroller.php,其中我想从users表中获取一个用户id的数据,以便我可以为sngle患者创建一个仪表板,这是我的代码:

PatientsController.php

 <?php 


 namespace App\Controller;

 use App\Controller\AppController;
 use Cake\Event\Event;
 use Cake\Network\Exception\NotFoundException;
 use Cake\ORM\TableRegistry;
 class PatientsController extends AppController
 { 


     public function isAuthorized($user)
 {
  return true;

   }

  public function index (){

 echo $this->Auth->user('id');
 $users = TableRegistry::get('Users');
 $users->find('all')->where(['id' => 4]);
 $this->set('users', $users);
 }

我想在我的Index.ctp中获取用户名生物和个人资料信息我正在尝试使用查询构建器传递数据但我很困惑所以任何帮助

3 个答案:

答案 0 :(得分:3)

因此,您的方法,技术以及代码都存在许多问题。

<强>方法
http://book.cakephp.org/3.0/en/controllers.html
如果您想获得单个患者记录,您应该在控制器中使用view()方法。因此,您需要创建一个名为view()的新方法,您可以在其中返回记录。在大多数情况下,此方法应将id作为参数。

<强>表格
http://book.cakephp.org/3.0/en/orm/table-objects.html
在CakePHP中,默认情况下将加载与控制器关联的表。因此,无需使用TableRegistry来加载表格。

获取数据
http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html
当您寻找单个记录时,您有两个选择。您可以使用带有first()的查找。

$this->Patients->find()
   ->where(['id' => $id])
   ->first();

或者您可以使用get(),如果找不到记录,则会引发异常。

$this->Patients->get($id);

加入相关数据
http://book.cakephp.org/3.0/en/orm/associations.html
如果要将数据加入到用户,那么您将需要使用表来管理数据,然后可以使用数据库中的外键来控制数据。这会更改您的查找,以包含contain()来电。

$this->Patients->find()
   ->where(['id' => $id])
   ->contain(['Profiles])
   ->first();

在视图中输出数据
您可以将查找结果设置为视图,然后使用您设置的变量循环或输出。在您的情况下$user

<强>摘要
总的来说,你可以看到你有很多想念。希望这有助于您走上正轨。

答案 1 :(得分:2)

鉴于这基本上是你在这里要求完全相同的第三个问题(获得查询的结果),我将指出你应该阅读的这些非常有用的资源:

教程:http://book.cakephp.org/3.0/en/tutorials-and-examples.html

他们基本上拥有了解查询如何工作以及如何在视图和表单中使用它们所需的一切。

ORM手册:http://book.cakephp.org/3.0/en/orm.html

您将找到大量获取数据并在检索数据后使用它的示例。

答案 2 :(得分:2)

我找到了此查询的解决方案:此类问题的完整代码: PatientsController.php

<?php 
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Event\Event;
   use Cake\Network\Exception\NotFoundException;
   use Cake\ORM\TableRegistry;

   class PatientsController extends AppController { 
       public function isAuthorized($user) {
           return true;
       }

       public function index () {
          $id = $this->Auth->user('id');
          $articles = TableRegistry::get('Users');
          $query = $articles->find()
              ->where(['id' => $id]);

          $this->set(compact('query'));
       }
    }

对于Index.ctp

 <!-- File: src/Template/Articles/index.ctp  (edit links added) -->

  <h1>Patient Dashboard</h1>
  I am patient

  <?php  
  foreach ($query as $row) {
     echo $row->username ,$row->password;
  }
  ?>

如果你只是想在cakephp中从程序性php转到oops,这种解决方案非常有用。