LoginSignup
1
2

More than 5 years have passed since last update.

cakephp3 belongsToMany で タグを複数持つものを検索

Last updated at Posted at 2017-04-10

複数の SiteTable は 複数の Tag を持つって関係。
いわば belongsToMany。

ここで
ラーメンとつけめん。
両方のタグを持つサイトを検索したい。

そんな場合はこう。

・SitesController.php

    public function test()
    {
        $tagName = ['ラーメン','つけめん'];

        $query = TableRegistry::get('Sites')->find();

        $res = $query
            ->matching('Tags', function ($q) use ($tagName) {
                return $q->where(['Tags.name IN' => $tagName]);
            })
            ->group(['Sites.id'])
            ->having([
                $this->Sites->query()->newExpr()->eq('COUNT(DISTINCT Tags.name)', count($tagName))
            ])

            ->all()->toArray();

        pr($res);

        $this->autoRender = false;
    }

これでラーメンとつけめん。両方のタグを持つサイトのみ取得できる。

つづいて、SearchPluginを使う場合


$search
    ->add('tag', 'Search.Callback', [


        'callback' => function ($query, $args, $filter) {

//                カンマまたは " ", \r, \t, \n , \f などの空白文字で句を分割する。
            $tags = preg_split("/[\s,]/",$args['tag']);

            $query->matching('Tags', function ($q) use ($tags) {
                return $q->where(['Tags.name IN' => $tags]);
            })
                ->group(['Sites.id'])
                ->having([
                    $query->newExpr()->eq('COUNT(DISTINCT Tags.name)', count($tags))
                ]);

        }
    ]);

1
2
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
1
2