我尝试通过与CakePHP的两个模型关系检索一些数据。模型及其关联如下:
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我想在用户执行 find()操作时返回用户的技能模型,现在它不返回。这是我针对 User 模型执行的查找调用:
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%" ) ) );它会返回用户数据和个人资料数据,但不会返回任何技能数据。我尝试将递归设置为 2 或 3 也没有帮助。我可以得到技能数据的唯一方法是如果我对 Profile 模型运行 find(),但我可以'这样做。为了说明这里的相关模型及其关系:
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.
推荐答案使用 CakePHP的可控行为。您的查找将如下所示:
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'.
更多推荐
通过两个模型关系检索数据
发布评论