php - Count the containing entities with cakephp 3.x -
im stuck while trying count entities , order set of results after that.
i have connected models each other:
// productstable $this->belongstomany('users', [ 'through' => 'productsusers', 'join_table' => 'products_users' ] ); // userstable $this->hasmany('products', [ 'through' => 'productsusers', ] ); // productsuserstable $this->belongsto('users'); $this->belongsto('products');
by query, products including users:
$products = $this->products->find() ->contain([ 'users', 'productcategories' ]);
it looks that:
products -> product 1 -> user1, user2, user 3 -> product 2 -> user1, user 3
now want sort result. tries fail.
i tried this:
$products = $this->products->find() ->contain([ 'users', 'productcategories' ]) ->select([ 'users_count' => $this->products->find()->func()->count('users') ])->order(['users_count' => 'asc']) ->select($this->products);
but no success. $products->users_count includes users.
i happy hint.
you should try counter cache:
it possible though make work belongstomany associations. need enable countercache behavior in custom through table configured in association options. see how configure custom join table using ‘through’ option.
this eliminates need compute on fly , have field user & product count in products & users table respectively.
Comments
Post a Comment