CakePHP语法从$Auth检索相关字段
CakePHP3.7。 这里是我的“用户”表:CakePHP语法从$Auth检索相关字段,php,mysql,cakephp,Php,Mysql,Cakephp,CakePHP3.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 {
<?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)
{
...
}
}
现在,我想通过customer_id在控制器和模板中检索相关字段,例如:
$this->Auth->user('customer_id')); // <--- WORKS
$this->Auth->user('Customers.company_name')); // <--- ???
我不明白必须使用什么语法通过外键customer_id导航才能读取Customers表中的其他字段
当然,我可以使用变通方法:
像上面那样检索“customer\u id”值
为该id创建“客户”筛选查询
阅读其他字段
但是我想这不是最好的方法。您需要包含包含客户记录的内容
不过,请注意,整个Auth组件已弃用,将在版本4中用单独的和中间件插件替换
$this->Auth->user('customer_id')); // <--- WORKS
$this->Auth->user('Customers.company_name')); // <--- ???