蛋糕PHP 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
例如在控制器和模板中检索关联的字段:
$this->Auth->user('customer_id')); // <--- WORKS
$this->Auth->user('Customers.company_name')); // <--- ???
我不明白我必须使用什么语法通过外键 ( customer_id
) “导航”才能读取Customers
表中的其他字段。
当然,我可以使用一种解决方法:
但我想这不是最好的方法。
您将需要自定义您的 Auth finder 查询以包括包含客户记录。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句