1
votes

I have an Entries table with users_id as a foreign key to the Users table.

I have set the belongsTo association in the EntriesTable like so:

$this->belongsTo('Users', [
    'foreignKey' => 'user_id',
    'joinType' => 'INNER'
]);

After that I wrote this in the EntriesController:

$entries = TableRegistry::get('Entries');
$query = $entries->findByTitle($title)
    ->contain(['Users']);
$entry = $query->first();
$this->set('entry', $entry);

In the VIEW template of the Entries I have to show the username field of the user that wrote the Entry.

I am aware that in previous versions of CakePHP 1, I could just write $entry['User']['username'] to retrieve the username of the User who wrote the Entry. Now that I am using CakePHP 3.6, it doesn't seem to work. How do I perform the same task in CakePHP 3?

2
check in your controller debug($entry); Then see what is the data showing.Alimon Karim
Would you add your view method too ?Alimon Karim

2 Answers

1
votes

You can write like below

In controller

public function view($title)
{
    $entry = $this->Entries->findByTitle($title)->contain(['Users']);
    $entry = $entry->first();
    $this->set('entry', $entry);
}

OR

public function view($title)
{
    $query = $this->Entries->find('all', [
        'where' => ['Entries.title' => $title],
        'contain' => ['Users']
    ]);
    $entry = $query->first();

    $this->set('entry', $entry);
}

In view

<?= $entry->user->username ?>
0
votes

So in cakephp you were loading Model of its controller, which is done as default,you can directly create an find() method in same controller,if you want to find from other table/ model you can do is-

a. $this->Entries->otherTableName()->find()->all();

b. $tableName= $this->loadModel('tableName'); $tableName->find();