Reputation: 5038
CakePHP 3.7. Here my 'Users' table:
<?php
namespace App\Model\Table;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Association\BelongsTo;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Customers', [
'foreignKey' => 'customer_id',
'joinType' => 'LEFT'
]);
}
public function validationDefault(Validator $validator)
{
...
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
$rules->add($rules->existsIn(['customer_id'], 'Customers'));
return $rules;
}
}
and 'Customers' table:
<?php
namespace App\Model\Table;
use App\Model\Entity\Customer;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Association\HasMany;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class CustomersTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('customers');
$this->setDisplayField('company_name');
$this->setPrimaryKey('id');
$this->hasMany('Users', [
'foreignKey' => 'customer_id'
]);
}
public function validationDefault(Validator $validator)
{
...
}
}
Here the 'login' method in UsersController:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'Products', 'action' => 'index']);
}
$this->Flash->error(__('Username or password is incorrect.'));
}
}
Well, now I want to retrieve in both controllers and templates the associated fields through customer_id
, example:
$this->Auth->user('customer_id')); // <--- WORKS
$this->Auth->user('Customers.company_name')); // <--- ???
I don't understand what syntax I have to use to "navigate" via foreign key (customer_id
) in order to read the other fields in the Customers
table.
Of course I can use a workaround:
But I guess this isn't the best approach.
Upvotes: 0
Views: 33
Reputation: 5099
You will need to customize your Auth finder query to include containing the customer record.
Beware, though, that the entire Auth component is deprecated, and will be replaced in version 4 with the separate authentication and authorization middleware plugins.
Upvotes: 1