CakePHP 3.7。 这是我的“用户”表:
<?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;
}
}
和“客户”表:
<?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)
{
...
}
}
这是 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.'));
}
}
好吧,现在我想通过 customer_id
在 Controller 和模板中检索关联字段,例如:
$this->Auth->user('customer_id')); // <--- WORKS
$this->Auth->user('Customers.company_name')); // <--- ???
我不明白必须使用什么语法通过外键 (customer_id
)“导航”才能读取 Customers
表中的其他字段。
当然我可以使用解决方法:
- 检索“customer_id”值(如上)
- 针对该 ID 创建“客户”过滤查询
- 阅读其他字段
但我想这不是最好的方法。
最佳答案
您需要customize your Auth finder query包括包含客户记录。
但请注意,整个 Auth 组件已被弃用,并将在版本 4 中替换为单独的 authentication和 authorization中间件插件。
关于php - CakePHP 语法从 $Auth 检索关联字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59345336/