访问关联表的不同方法

时间:2016-05-07 07:46:10

标签: php cakephp-3.0 data-retrieval

我收到查询结果后,访问我在表类中加入的关联表时遇到问题 debug($ query):

    src\Model\Table\ComlibsTable.php (line 30)
       [
       (int) 0 => object(App\Model\Entity\Comlib) {

    'id' => (int) 1,
    'question' => 'how to kill someone?',
    'answer' => (int) 2,
    'asked' => (int) 90,
    'tags' => 'kill,proffesional killer',
    'created' => null,
    'modified' => null,
    'answers' => [
        (int) 0 => object(App\Model\Entity\Answer) {

            'id' => (int) 1,
            'question_id' => (int) 1,
            'answer' => 'the crackpot will attack the will of the darkness and then i starve',
            'rate' => (float) 11.2,
            'view' => (int) 22,
            'helpful' => '11|22',
            '[new]' => false,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[invalid]' => [],
            '[repository]' => 'Answers'

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

}
]   

现在我知道我可以访问Comlib实体,如:$ query [0] ['question']; 但我想知道是否有其他方式来访问像$ query->问题的实体; 以及我如何访问答案实体, 我的控制器代码:

<?php
namespace App\Controller;

use App\Controller\AppController;

class ComlibsController extends AppController {

    public function index() {

    }

    public function getResult(){

        $this->viewBuilder()->layout('comlib');
        $live_req = $this->request->data['searchBox'];
        $query = $this->Comlibs->LFM($live_req);

        $this->set('question',$query[0]['question']); // does work
        $this->set('answer',$query['answers'][0]['id']); // does not work

    }
}

LFM功能

public function LFM( $live_req) {

$query = $this->find()->where(['question' => $live_req])->contain(['Answers']);
$query = $query->toArray();
debug($query);
//include 5 answer
return $query;

    }
}

tnx获取任何帮助

1 个答案:

答案 0 :(得分:0)

好吧我尝试了不同的方法后想出来,因为它是一个数组我所要做的就是以正确的方式访问数组,那就是:

If IsNull(Me![Permanent Address].Value) Then
    Me![Permanent Address].Value = Me![Present Address].Value
End If

现在我可以访问这些值,但似乎这不是访问数组属性的正确方法,还有另外一种方法吗?我如何从$ query [0]中删除[0]?