如何从 CakePHP 3.x 中的关联 table 作为对象接收数据(当前作为数组接收)

How to receive data from associated table in CakePHP 3.x as object(currently receiving as an array)

我正在尝试使用 belongsTo 关联表格: http://book.cakephp.org/3.0/en/orm/associations.html#belongsto-associations

我的

中有此代码

JobsController.php:

class JobsController extends AppController
{
    public $name = 'Jobs';

    /**
     * Index method
     *
     * @return void
     */
    public function index()
    {
        //Get Jobs info
        $getjobs = TableRegistry::get('Jobs');
        $jobs = $getjobs->find('all')->contain(['Types']);
        $this->set('jobs',$jobs);
    }
}

JobsTable.php:

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class JobsTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('jobs');
        $this->belongsTo('types', [
            'foreignKey' => 'type_id',
            'joinType' => 'INNER',
        ]);
    }

}

TypesTable.php:

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class TypesTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('types');
    }

}

我正在接收所需的数据,但不是像手册中所写的那样将其作为对象接收,而是作为数组接收,这不是应该的。

So now I'm accessing it like this(because its an array with name types):

<?php foreach($jobs as $job) : ?>
        <?php var_dump($job->types['color']); ?>
<?php endforeach; ?>

But instead it supposed to be like this(according to docs it should be an object with name type):

<?php foreach($jobs as $job) : ?>
    <?php var_dump($job->type->color); ?>
<?php endforeach; ?>

我做错了什么?

注意你的大小写,关联定义为 types,但你将其包含为 Types,这将导致关联数据被水化的结果集分组。

$this->belongsTo('Types', /* ... */);

这应该可以解决问题。

我想这种行为是否会被视为有问题甚至是错误是值得商榷的。