How to retrieve associations together with authenticated user data?

前端 未结 1 399
不思量自难忘°
不思量自难忘° 2020-12-10 20:54

I have a Users table and a UsersProfiles table - the two are obviously related and the user table stores basic user_id, username

相关标签:
1条回答
  • 2020-12-10 21:15

    The contain option

    Before CakePHP 3.1, use the contain option

    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'contain' => ['UsersProfiles']
            ]
        ]
    ]);
    

    A custom finder

    As of 3.1 you can use the finder option to define the finder to use for building the query that fetches the user data

    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'finder' => 'auth'
            ]
        ]
    ]);
    

    In your table class

    public function findAuth(\Cake\ORM\Query $query, array $options)
    {
        return $query->contain(['UsersProfiles']);
    }
    

    Both solutions

    will ensure that the data returned by AuthComponent::identify() will contain the associated UsersProfiles.

    See also

    • Cookbook > ... Components > Authentication > Configuring Authentication Handlers
    • Cookbook > ... Components > Authentication > Customizing find query
    0 讨论(0)
提交回复
热议问题