【问题标题】:Access data after sql query in CakePHPCakePHP中sql查询后访问数据
【发布时间】:2016-11-21 20:33:51
【问题描述】:

我已经执行了下面的 sql 语句,它已经从表中获取了相关的行。

sql;

$user = $this->UserVerifications
                ->find()
                ->where(['code' => $hash])
                ->all();

它正在从表“UserVerifications”中获取“code”列等于“hash”值的行。此位有效,输出见下文。

debug($user);
\src\Controller\UsersController.php (line 57) object(Cake\ORM\ResultSet) {

'items' => [
    (int) 0 => object(App\Model\Entity\UserVerification) {

        'id' => (int) 23,
        'code' => '4206e38996fae4028a26d43b24f68d32',
        'date_created' => object(Cake\I18n\FrozenTime) {

            'time' => '2016-11-21T18:48:45+00:00',
            'timezone' => 'UTC',
            'fixedNowTime' => false

        },
        '[new]' => false,
        '[accessible]' => [
            '*' => true
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[errors]' => [],
        '[invalid]' => [],
        '[repository]' => 'UserVerifications'

    }
]

}

根据 CakePHP 网站,或者至少按照我的阅读方式,我应该能够通过执行以下操作来访问 id 的值;

echo $user->id;

注意(8):未定义属性:Cake\ORM\ResultSet::$id [APP/Controller\UsersController.php, line 58]

我错过了一些简单的东西吗?

【问题讨论】:

    标签: php arrays cakephp


    【解决方案1】:

    您的 $user 是一个集合/ResultSet,而不是 UserVerifications 实例。

    http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

    你应该迭代它,比如:

    foreach($user as $u) {
        echo $u->id;
    }
    

    【讨论】:

      【解决方案2】:

      如果您只需要表格中的特定行,试试这个:

      $user = $this->UserVerifications
                  ->find()
                  ->where(['code' => $hash])
                  ->first();
      

      现在你可以使用:

      $user->id;
      

      访问 id 的值等等。如果您需要表格中的多行,请使用@Felippe 的答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-04
        • 2013-03-13
        • 1970-01-01
        相关资源
        最近更新 更多