通过两个模型关系检索数据

编程入门 行业动态 更新时间:2024-10-10 23:18:41
本文介绍了通过两个模型关系检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试通过与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'.

更多推荐

通过两个模型关系检索数据

本文发布于:2023-07-14 10:33:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104120.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   两个   关系   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!