简体   繁体   English

CakePHP - 如何从控制器中的另一个模型中检索数据

[英]CakePHP - How to retrieve data from another model in controller

Currently i have 2 models. 目前我有2个型号。 Users and Appbreak. 用户和Appbreak。 They have associations of Users has many appbreak. 他们有用户协会有很多appbreak。 Appbreaks belongs to users In my appbreak controller, there is a approve function which is called when a button from the view page is pressed. Appbreak属于用户在我的appbreak控制器中,有一个批准功能,当按下视图页面中的按钮时会调用该功能。

In this function, i will need to update a value in the table of appbreak and a value in users table. 在这个函数中,我需要更新appbreak表中的值和users表中的值。 I'm able to update value in appbreak by using the following: 我可以使用以下内容更新appbreak中的值:

$this->Appbreak->id = $id;
    $this->Appbreak->set('approve', 'Yes');
    $this->Appbreak->save();

However, i'm unable to pull the required data value from users table. 但是,我无法从users表中提取所需的数据值。 <-- need to do so as i need to do some calculations before passing back the calculated value. < - 需要这样做,因为我需要在传回计算值之前进行一些计算。

Am i able to get data from another model using the request method? 我能使用请求方法从另一个模型获取数据吗? Or do i need to use the find method? 或者我需要使用find方法吗? If i use the find method, am i able to update the the values and save it back into the database? 如果我使用find方法,我能够更新值并将其保存回数据库吗?

You can use any number of models in a controller . 您可以在控制器中使用任意数量的模型。 Declare the 'uses' array in controller 在控制器中声明'uses'数组

<?php
class DemoController extends AppController{
    public $uses=array('Appbreak','User');
}
?>

To get data from AppBreak model use find method of 要从AppBreak模型获取数据, AppBreak使用find方法
$this->AppBreak object $this->AppBreak对象
Similarly to get data for User use find method of 同样为User使用find方法获取数据
$this->User object $this->User对象

Use find() to get your values, and if you need to update the values, use save(). 使用find()获取值,如果需要更新值,请使用save()。 Like so: 像这样:

$this->Appbreak->Users->find('first', $params); 

(as described here ) (如所描述的在这里

To save, simply create an array with at least the relevant record id. 要保存,只需创建一个至少包含相关记录ID的数组。 Include any fields you want to update, and then call the save method on the array like so: 包括要更新的任何字段,然后在数组上调用save方法,如下所示:

$data = array('id' => 10, 'title' => 'My new title');
// This will update Recipe with id 10
$this->Recipe->save($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM