CakePHP 语法从 $Auth 检索关联字段

标记

蛋糕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表中的其他字段

当然,我可以使用一种解决方法:

  1. 检索“customer_id”值(如上)
  2. 为该 ID 创建一个关于“客户”过滤的查询
  3. 读取其他字段

但我想这不是最好的方法。

格雷格·施密特

您将需要自定义您的 Auth finder 查询以包括包含客户记录。

但请注意,整个 Auth 组件已弃用,并将在第 4 版中替换为单独的身份验证授权中间件插件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章