Retrieving data through two model relationships

▼魔方 西西 提交于 2019-12-12 03:56:09

问题


I'm trying to retrieve some data through two model relationships with CakePHP. The models and their associations are as follows:

User hasOne Profile HABTM Skill

I would like the user's skills to be returned when I do a find() operation on the User model, and right now it isn't returned. Here's my find call which is being executed against the User model:

$this->paginate = array(
    'conditions' => array(
        'OR' => array(
            'Profile.firstname LIKE' => "%$q%",
            'Profile.lastname LIKE' => "%$q%"
        )
    )
);

It's returning user data and profile data, but not any skill data. I tried setting recursive to 2 or 3, but that doesn't help either. The only way I can get skill data is if I run find() against the Profile model, but I can't do that. For clarification here's the relevant models and their relationships:

// app/Model/User.php
class User extends AppModel {
    public $hasOne = 'Profile';
}

// app/Model/Profile.php
class Profile extends AppModel {
    public $belongsTo = 'User';
    public $hasAndBelongsToMany = 'Skill';

// app/Model/Skill.php
class Skill extends AppModel {
    public $hasAndBelongsToMany = 'Profile';

Can anyone help me get the users skills when retrieving user data? Thanks.


回答1:


Use CakePHP's Containable Behavior. Your find will then look something like this:

$this->User->find('all',array(
    'conditions' => array(
        'OR' => array(
            'Profile.firstname LIKE' => "%$q%",
            'Profile.lastname LIKE' => "%$q%"
        )
    ),
    'contain' => array(
        'Profile' => array(
            'Skill'
        )
    )
));

MUCH simpler, easier to read, and voila - you get the data you want without needing to use the dreaded 'recursive'.



来源:https://stackoverflow.com/questions/15851898/retrieving-data-through-two-model-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!