官术网_书友最值得收藏!

Modifying binding conditions for a find

This recipe shows how to use Containable to change the conditions used to fetch data related to a model through a binding.

Getting ready

We need to have Containable added to our models, and we also need some sample models and data to work with. Follow the recipe, Adding Containable to all models, and the Getting ready section of the recipe, Modifying binding parameters for a find.

How to do it...

If we want to obtain the first User record together with the published Article records that user owns, but ordered by latest articles first, and limiting some of the returned fields, we use the conditions binding setting:

$user = $this->User->find('first', array(
'contain' => array(
'Article' => array(
'fields' => array('Article.title'),
'conditions' => array( 'Article.published' => 1 )
)
)
));

Using our sample data, the preceding query will result in the following array structure:

array(
'User' => array(
'id' => '1',
'name' => 'John Doe',
'email' => 'john.doe@example.com',
),
'Article' => array(
array(
'title' => 'John\'s Post 1',
'user_id' => '1'
),
array(
'title' => 'John\'s Post 2',
'user_id' => '1'
),
array(
'title' => 'John\'s Post 4',
'user_id' => '1'
)
)
)

How it works...

The conditions binding setting is another binding parameter, such as those shown in the recipe, Modifying binding parameters for a find. As such, the Containable behavior uses the built-in bindModel() method defined in CakePHP's Model class to alter the binding conditions defined in the contain find operation.

主站蜘蛛池模板: 鹤山市| 宁蒗| 称多县| 夹江县| 绥芬河市| 六盘水市| 天津市| 遂平县| 高清| 咸阳市| 咸丰县| 奇台县| 赤峰市| 洞头县| 上饶市| 留坝县| 柯坪县| 宜兰县| 吉安县| 文成县| 阿鲁科尔沁旗| 九龙县| 澜沧| 札达县| 永登县| 驻马店市| 胶南市| 靖宇县| 印江| 广安市| 建德市| 钟祥市| 汾西县| 乃东县| 通山县| 阳曲县| 蒲城县| 鱼台县| 松阳县| 南充市| 涿州市|