Friday, January 14, 2022

[FIXED] Table "App\Model\Table\UsersTable" is not associated with "id" cakephp 3

Issue

I'm getting this error 'Table "App\Model\Table\UsersTable" is not associated with "id" ', can anyone help how to solve it?

Here is the code of my documents table:

class DocumentsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->belongsTo('Users');
        //$this->setForeignKey('user_id');
        $this->setTable('documents');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');
    }
}

and here is the code of users table:

class UsersTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->hasMany('Documents');
        $this->setTable('users');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');
    }
}

and here is what the error looks like:

enter image description here

EDIT: According to the url I'm trying to reach the academics controller, in which I'm loading the documents table.

In calander.ctp, one of the functions of academics table, I use the following code:

use Cake\ORM\TableRegistry;
$admin = TableRegistry::get('Users');
$name = $admin->find()->select(['name'])->where([$admin->id => $doc['user_id']])->first();
echo $name;

Solution

$admin is a table object, but you're trying to access $admin->id in your where clause. id is not a property of table objects, and even if it was, this wouldn't be useful. It should be where(['Users.id' => $doc['user_id']]).



Answered By - Greg Schmidt

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.