0

I have a Table A related many to many with a Table B and I want to know how many related rows I have in B with a given A entity. In SQL it would be something like this:

SELECT COUNT(*) FROM AB WHERE A_id=1;

I thought that I should place it in the model of A with a Virtual Field that retrieves the count, but I didn´t find a way to use the model itself to get the related B rows.

I tried with

$this->contain(['B'])->count()

But it didn't work because 'contain' is undefined. So, how should I get the count?

Juan De la Cruz
  • 436
  • 6
  • 17
  • 1
    Possible duplicate of [CakePHP 3: CounterCache with BelongsToMany](http://stackoverflow.com/questions/32948513/cakephp-3-countercache-with-belongstomany) – Salines May 24 '16 at 06:53
  • @Salines Well, it seems that it makes what i wanted but, why should I store the count in the relationship table? – Juan De la Cruz May 24 '16 at 13:57
  • Your relationship Model with CounterCache behavior are not store count in own table, but related, in your case in A table. – Salines May 24 '16 at 14:19

1 Answers1

0

Make sure that u put the association in both of your models initialize method and dont call contain() on $this.

$query = $this->A->find();

numberOfRecords = $query->contain(['B'])->count;
Valentin Rapp
  • 432
  • 6
  • 11
  • "Call to a member function find() on null". It seems that the Entity doesn´t have an instance of the the Table collection that contains himself. – Juan De la Cruz May 24 '16 at 14:02
  • Please supply the model init. method and the controller method of A where you are calling the function. – Valentin Rapp May 25 '16 at 06:55