0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Cakephp2.x】HABTMの関係にある別モデルのpaginationをする

Last updated at Posted at 2019-09-26

状況

PostとTagが多対多の関係で、
TagsController内で指定したTagのidに該当している全てのPost達でPaginationをしたい。

やった方法

TagsController.php
    $tagId = 1; 
	$this->Paginator->settings = array(
		'conditions' => array('PostsTag.tag_id' => $tagId),
		'limit' => 5,
		'joins' => array(
			array(
				'table' => 'posts_tags',
				'alias' => 'PostsTag',
				'type' => 'INNER',
				'conditions' => array(
					'PostsTag.tag_id' => $tagId,
					'PostsTag.post_id = Post.id'
				)
			)
		),
	);
	$posts = $this->Paginator->paginate('Post');
	$this->set('posts', $posts);

自分のモデルに合わせて書き換えて頂ければサクッとpaginationが出来るはずです。
hasManyならjoinsは要りませんのでconditionsでそのまま別モデルの_idを指定すれば取って来れます。

参考にさせて頂いたサイト様
CakePHP how to retrieve HABTM data with conditions?
[アソシエーション: モデル同士を繋ぐ - 2.x - CakePHP Cookbook]
(https://book.cakephp.org/2.0/ja/models/associations-linking-models-together.html#)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?