# Calling a Function in Model A from Controller A

**URL:** https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814
**Category:** Uncategorized
**Created:** [July 26, 2016, 11:26am UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814 "2016-07-26T11:26:10Z")
**Posts on this page:** 8
**Page:** 1

<div class="post-metadata">

### Author: ![ishonowo](https://avatars.discourse-cdn.com/v4/letter/i/5daacb/32.png) [@ishonowo](https://discourse.cakephp.org/u/ishonowo)
#### Post date: [July 26, 2016, 11:26am UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/1 "2016-07-26T11:26:10Z")

</div>

Good day.

I am new to CakePHP. I am using 3.2.6. Kindly explain with sample code how I can call a function in the Model from the Controller for the Model or direct me to a tutorial that will teach this.

Thanks.

---

<div class="post-metadata">

### Author: ![Din0saur](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/din0saur/32/323_2.png) [@Din0saur](https://discourse.cakephp.org/u/Din0saur)
#### Post date: [July 26, 2016, 7:40pm UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/2 "2016-07-26T19:40:34Z")

</div>

AnyTable.php

function myFunction() {  
}

in AnyController.php  
(since we are talking same table “Any” here) you can just

$this-\>any-\>myFunction();

If you are in any other controller, you need to load the proper model before:

AnyOtherController.php

$anyTable = $this-\>loadModel(‘Any’);  
$anyTable-\>myFunction();

---

<div class="post-metadata">

### Author: ![ishonowo](https://avatars.discourse-cdn.com/v4/letter/i/5daacb/32.png) [@ishonowo](https://discourse.cakephp.org/u/ishonowo)
#### Post date: [July 26, 2016, 7:45pm UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/3 "2016-07-26T19:45:33Z")

</div>

find below functions in model

\<?php namespace App\Model\Table; use App\Model\Entity\Payment; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; use Cake\ORM\TableRegistry; /\*\* \* Payments Model \* \* @property \Cake\ORM\Association\BelongsTo $Members \* @property \Cake\ORM\Association\BelongsTo $PaymentTypes \*/ class PaymentsTable extends Table { /\*\* \* Initialize method \* \* @param array $config The configuration for the Table. \* @return void \*/ public function initialize(array $config) { parent::initialize($config); $this-\>table('payments'); $this-\>displayField('id'); $this-\>primaryKey('id'); $this-\>belongsTo('Members', ['foreignKey' =\> 'member\_id', 'joinType' =\> 'INNER']); $this-\>belongsTo('PaymentTypes', ['foreignKey' =\> 'payment\_type\_id', 'joinType' =\> 'INNER']); } /\*\* \* Default validation rules. \* \* @param \Cake\Validation\Validator $validator Validator instance. \* @return \Cake\Validation\Validator \*/ public function validationDefault(Validator $validator) { $validator -\>integer('id') -\>allowEmpty('id', 'create'); $validator -\>allowEmpty('amount'); return $validator; } /\*\* \* Returns a rules checker object that will be used for validating \* application integrity. \* \* @param \Cake\ORM\RulesChecker $rules The rules object to be modified. \* @return \Cake\ORM\RulesChecker \*/ public function buildRules(RulesChecker $rules) { $rules-\>add($rules-\>existsIn(['member\_id'], 'Members')); $rules-\>add($rules-\>existsIn(['payment\_type\_id'], 'PaymentTypes')); return $rules; } public function findTotalPaid(Query $query) { $payments=TableRegistry::get('Payments'); $query = $payments-\>find() -\>select(['member\_id','amount\_paid' =\> $query-\>func()-\>sum('amount')]) -\>where(function ($q) { $q-\>notIn('amount', ['SICK','New','Excuse']) -\>isNotNull('amount');}) -\>group(['member\_id']); //-\>execute(); return $query; } /\*select m.id,sum(CAST(p.amount AS UNSIGNED)) as amount\_paid from payments p join members m on p.member\_id=m.id where p.amount not in ('SICK','New','Excuse') and p.amount is not null and p.member\_id=16 group by m.id;\*/ public function findTotalOwed(Query $query) { $payments=TableRegistry::get('Payments'); $query = $payments-\>find() -\>contain(['PaymentTypes','Members']) -\>select(['member\_id','amount\_due' =\> $query-\>func()-\>sum('PaymentTypes.amount\_due')]) -\>where(function ($q) { $q-\>isNull('Payments.amount');}) -\>group(['member\_id']); //-\>execute(); return $query; } /\*select m.id,sum( t.amount\_due) as amount\_due from payments p join payment\_types t on t.id=p.payment\_type\_id join members m on m.id=p.member\_id where p.amount is null group by m.id;\*/ } //The commented sql is what I will like to achieve. find below the controller action calling it \<?php namespace App\Controller; use App\Controller\AppController; /\*\* \* Payments Controller \* \* @property \App\Model\Table\PaymentsTable $Payments \*/ class PaymentsController extends AppController { /\*\* \* Index method \* \* @return \Cake\Network\Response|null \*/ public function index() { $this-\>paginate = ['contain' =\> ['Members', 'PaymentTypes'] ]; $userId=$this-\>Auth-\>user('id'); $role=$this-\>Auth-\>user('role'); $branchId=$this-\>Auth-\>user('branch\_id'); if ($role==='member') { $payments =$this-\>paginate = ['contain' =\> ['Members', 'PaymentTypes'], 'conditions' =\> ['Members.user\_id' =\> $userId] ]; } else if ($role==='branch\_admin') { $payments =$this-\>paginate= ['contain' =\> ['Members', 'PaymentTypes'], 'conditions'=\> ['Members.branch\_id'=\>$branchId], ]; } else { $payments = $this-\>paginate($this-\>Payments); } //$role=$this-\>Auth-\>user('role'); //$this-\>set('role',$role); //$this-\>set(compact('members')); //$this-\>set('\_serialize', ['members']); $amounts=$this-\>Payments-\>find('TotalPaid'); $amounts\_owed=$this-\>Payments-\>find('TotalOwed'); //$this-\>set(compact('payments')); $this-\>set('payments', $this-\>paginate($this-\>Payments)); $this-\>set('\_serialize', ['payments']); $this-\>set('amounts', $this-\>paginate($amounts)); $this-\>set('\_serialize', ['amounts']); $this-\>set('amounts\_owed', $this-\>paginate($amounts\_owed)); $this-\>set('\_serialize', ['amounts\_owed']); } find below the view displaying

#### \<?= \_\_('Paid Summary') ?\>
 \<?php foreach ($amounts as $amount): ?\> \<?php endforeach; ?\> 

| \<?= $this-\>Paginator-\>sort('Member Name') ?\> | \<?= $this-\>Paginator-\>sort('Amount Paid') ?\> |
| --- | --- |
| \<?= $amount-\>has('member') ? $this-\>Html-\>link($amount-\>member-\>surname.', '.$amount-\>member-\>first\_name.' '.$amount-\>member-\>middle\_name, ['controller' =\> 'Members', 'action' =\> 'view', $amount-\>member-\>id]) : '' ?\> | \<?= h($amount-\>amount\_paid) ?\> |

#### \<?= \_\_('Owed Summary') ?\>
 \<?php foreach ($amounts\_owed as $owed): ?\> \<?php endforeach; ?\> 

| \<?= $this-\>Paginator-\>sort('Member Name') ?\> | \<?= $this-\>Paginator-\>sort('Amount Owed') ?\> |
| --- | --- |
| \<?= $owed-\>has('member') ? $this-\>Html-\>link($owed-\>member-\>surname.', '.$owed-\>member-\>first\_name.' '.$owed-\>member-\>middle\_name, ['controller' =\> 'Members', 'action' =\> 'view', $owed-\>member-\>id]) : '' ?\> | \<?= h($owed-\>amount\_due) ?\> |

#### \<?= \_\_('Payment Details') ?\>
 \<?php foreach ($payments as $payment): ?\> \<?php endforeach; ?\> 

| \<?= $this-\>Paginator-\>sort('Name') ?\> | \<?= $this-\>Paginator-\>sort('amount') ?\> | \<?= $this-\>Paginator-\>sort('payment\_type') ?\> | \<?= \_\_('Actions') ?\> |
| --- | --- | --- | --- |
| \<?= $payment-\>has('member') ? $this-\>Html-\>link($payment-\>member-\>surname.', '.$payment-\>member-\>first\_name.' '.$payment-\>member-\>middle\_name, ['controller' =\> 'Members', 'action' =\> 'view', $payment-\>member-\>id]) : '' ?\> | \<?= ($payment-\>amount) ? h($payment-\>amount): 'Payment due' ?\> | \<?= $payment-\>has('payment\_type') ? $this-\>Html-\>link($payment-\>payment\_type-\>type\_name, ['controller' =\> 'PaymentTypes', 'action' =\> 'view', $payment-\>payment\_type-\>id]) : '' ?\> | \<?= $this-\>Html-\>link(\_\_('View'), ['action' =\> 'view', $payment-\>id]) ?\> \<?= $this-\>Html-\>link(\_\_('Edit'), ['action' =\> 'edit', $payment-\>id]) ?\> \<?= $this-\>Form-\>postLink(\_\_('Delete'), ['action' =\> 'delete', $payment-\>id], ['confirm' =\> \_\_('Are you sure you want to delete # {0}?', $payment-\>id)]) ?\> |

 \<?= $this-\>Paginator-\>prev('\< ' . \_\_('previous')) ?\> \<?= $this-\>Paginator-\>numbers() ?\> \<?= $this-\>Paginator-\>next(\_\_('next') . ' \>') ?\> 

\<?= $this-\>Paginator-\>counter() ?\>

find below error message

Warning (4096): Argument 1 passed to Cake\Database\Expression\QueryExpression::\_addConditions() must be of the type array, null given, called in C:\xampp\htdocs\umuakolomvillage\vendor\cakephp\cakephp\src\Database\Expression\QueryExpression.php on line 137 and defined [CORE\src\Database\Expression\QueryExpression.php, line 604]  
Warning (2): Invalid argument supplied for foreach() [CORE\src\Database\Expression\QueryExpression.php, line 610]  
Warning (4096): Argument 1 passed to Cake\Database\Expression\QueryExpression::\_addConditions() must be of the type array, null given, called in C:\xampp\htdocs\umuakolomvillage\vendor\cakephp\cakephp\src\Database\Expression\QueryExpression.php on line 137 and defined [CORE\src\Database\Expression\QueryExpression.php, line 604]  
Warning (2): Invalid argument supplied for foreach() [CORE\src\Database\Expression\QueryExpression.php, line 610]

I hope someone can direct me now.

---

<div class="post-metadata">

### Author: ![ishonowo](https://avatars.discourse-cdn.com/v4/letter/i/5daacb/32.png) [@ishonowo](https://discourse.cakephp.org/u/ishonowo)
#### Post date: [July 26, 2016, 7:53pm UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/4 "2016-07-26T19:53:44Z")

</div>

see view again. It did not come out right.

#### \<?= \_\_('Paid Summary') ?\>
 \<?php foreach ($amounts as $amount): ?\> \<?php endforeach; ?\> 

| \<?= $this-\>Paginator-\>sort('Member Name') ?\> | \<?= $this-\>Paginator-\>sort('Amount Paid') ?\> |
| --- | --- |
| \<?= $amount-\>has('member') ? $this-\>Html-\>link($amount-\>member-\>surname.', '.$amount-\>member-\>first\_name.' '.$amount-\>member-\>middle\_name, ['controller' =\> 'Members', 'action' =\> 'view', $amount-\>member-\>id]) : '' ?\> | \<?= h($amount-\>amount\_paid) ?\> |

#### \<?= \_\_('Owed Summary') ?\>
 \<?php foreach ($amounts\_owed as $owed): ?\> \<?php endforeach; ?\> 

| \<?= $this-\>Paginator-\>sort('Member Name') ?\> | \<?= $this-\>Paginator-\>sort('Amount Owed') ?\> |
| --- | --- |
| \<?= $owed-\>has('member') ? $this-\>Html-\>link($owed-\>member-\>surname.', '.$owed-\>member-\>first\_name.' '.$owed-\>member-\>middle\_name, ['controller' =\> 'Members', 'action' =\> 'view', $owed-\>member-\>id]) : '' ?\> | \<?= h($owed-\>amount\_due) ?\> |

#### \<?= \_\_('Payment Details') ?\>
 \<?php foreach ($payments as $payment): ?\> \<?php endforeach; ?\> 

| \<?= $this-\>Paginator-\>sort('Name') ?\> | \<?= $this-\>Paginator-\>sort('amount') ?\> | \<?= $this-\>Paginator-\>sort('payment\_type') ?\> | \<?= \_\_('Actions') ?\> |
| --- | --- | --- | --- |
| \<?= $payment-\>has('member') ? $this-\>Html-\>link($payment-\>member-\>surname.', '.$payment-\>member-\>first\_name.' '.$payment-\>member-\>middle\_name, ['controller' =\> 'Members', 'action' =\> 'view', $payment-\>member-\>id]) : '' ?\> | \<?= ($payment-\>amount) ? h($payment-\>amount): 'Payment due' ?\> | \<?= $payment-\>has('payment\_type') ? $this-\>Html-\>link($payment-\>payment\_type-\>type\_name, ['controller' =\> 'PaymentTypes', 'action' =\> 'view', $payment-\>payment\_type-\>id]) : '' ?\> | \<?= $this-\>Html-\>link(\_\_('View'), ['action' =\> 'view', $payment-\>id]) ?\> \<?= $this-\>Html-\>link(\_\_('Edit'), ['action' =\> 'edit', $payment-\>id]) ?\> \<?= $this-\>Form-\>postLink(\_\_('Delete'), ['action' =\> 'delete', $payment-\>id], ['confirm' =\> \_\_('Are you sure you want to delete # {0}?', $payment-\>id)]) ?\> |

 \<?= $this-\>Paginator-\>prev('\< ' . \_\_('previous')) ?\> \<?= $this-\>Paginator-\>numbers() ?\> \<?= $this-\>Paginator-\>next(\_\_('next') . ' \>') ?\> 

\<?= $this-\>Paginator-\>counter() ?\>

---

<div class="post-metadata">

### Author: ![ishonowo](https://avatars.discourse-cdn.com/v4/letter/i/5daacb/32.png) [@ishonowo](https://discourse.cakephp.org/u/ishonowo)
#### Post date: [July 26, 2016, 7:54pm UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/5 "2016-07-26T19:54:49Z")

</div>

Thanks. I just pasted some more info. I will be glad if you can assist.

---

<div class="post-metadata">

### Author: ![Din0saur](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/din0saur/32/323_2.png) [@Din0saur](https://discourse.cakephp.org/u/Din0saur)
#### Post date: [July 26, 2016, 11:17pm UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/6 "2016-07-26T23:17:12Z")

</div>

Man, your problems are completely out of the subject you propose. Even your first question (which I believe I could help) has no link at all with the problem you are showing now!

Put is simple, I thought I was able to help, but I’m not.

Just be give you some alternative:

The errors seems look like [http://qaoverflow.com/question/cakephp-3-x-hasmany-through-association-find/](http://qaoverflow.com/question/cakephp-3-x-hasmany-through-association-find/)

And the query, you can always use

$conn = ConnectionManager::get(‘default’);  
$query = “select fields from table where…”;  
$results = $conn-\>execute($query)-\>fetchAll(‘assoc’);

---

<div class="post-metadata">

### Author: ![ishonowo](https://avatars.discourse-cdn.com/v4/letter/i/5daacb/32.png) [@ishonowo](https://discourse.cakephp.org/u/ishonowo)
#### Post date: [July 27, 2016, 7:02am UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/7 "2016-07-27T07:02:25Z")

</div>

Thanks for responding.

The issue is with the calls below

$amounts=$this-\>Payments-\>find(‘TotalPaid’);  
$amounts\_owed=$this-\>Payments-\>find(‘TotalOwed’);

I don’t know how to call the function findTotalPaid(Query $query) and findTotalOwed(Query $query). I don’t know how to pass the Query $query to the function or get ride of it completely.

I will appreciate if you can help.

---

<div class="post-metadata">

### Author: ![Din0saur](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/din0saur/32/323_2.png) [@Din0saur](https://discourse.cakephp.org/u/Din0saur)
#### Post date: [July 17, 2017, 9:16pm UTC](https://discourse.cakephp.org/t/calling-a-function-in-model-a-from-controller-a/814/8 "2017-07-17T21:16:07Z")

</div>

I believe you had already solved your problem, I’m rigth? Sorry, I stay out of forum for too long.

$amounts=$this-\>Payments-\>find(‘TotalPaid’);  
$amounts\_owed=$this-\>Payments-\>find(‘TotalOwed’);

Should be

$amounts = $this-\>Payments-\>TotalPaid()  
$amounts\_owed = $this-\>Payments-\>TotalOwed()

Assuming this-\>Payments is your Payment model. If not, my first answer aplies:

$Payments = $this-\>loadModel(‘Payments’);  
$amounts = $Payments-\>TotalPaid();  
$amounts\_owed = $Payments-\>TotalOwed()
