如何使用find方法限制关联模型的字段 [英] How to limit the fields of the associated models using find method

查看:99
本文介绍了如何使用find方法限制关联模型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用户模型和文章模型。一个用户有很多文章。因此,当我查询用户时,将检索文章表的所有字段。我只想限制文章标题。

I have user model and articles model. An User hasMany articles. So when I query for a user, all fields for article table is retrieved. I want to limit it just title of articles.

$user = $this->User->find('all', array('conditions' => array('User.id' => $id), 'fields' => array('User.firstName', 'Article.title')));

该字段适用于用户模型。但这不适用于关联的模型。引发错误

The fields works fine for user model. But it does not work for associated models. throws error

SQL Error: 1054: Unknown column 'Article.title' in 'field list' 

感谢您的帮助。

推荐答案

最好使用可容纳,它也很简单:

You're better of using Containable, and it's just as easy:

$this->User->Behaviors->attach('Containable');
$user = $this->User->find('all', array('conditions' => array('User.id' => $id), 'contain' => array('Article.title'), 'fields' => array('User.firstName')));

这篇关于如何使用find方法限制关联模型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆