1
2

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.

laravel-admin で多対多リレーションの項目を multipleSelect() で AND 検索する方法

Posted at

処理の流れは以下のとおりです。

  1. grid画面でmultipleSelect()を使用して一つの項目で複数選択できるようにします
  2. multipleSelect()で取得した配列で中間テーブルを検索します
  3. 中間テーブルで多対多で紐づくテーブルのIDを検索し、全てヒットするもう一つの外部キーをgroupbyとhavingを使用して特定します
  4. $query->whereIn に特定した外部キーの配列を渡してフィルタします
  • ActivationKeyCreateHistoryProduct.php (中間テーブル)
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ActivationKeyCreateHistoryProduct extends Model
{
    protected $table = 'activation_key_create_history_product';

    public static function ActivationKeyCreateHistoryProducts($productIds)
    {
        return ActivationKeyCreateHistoryProduct::whereIn('product_id', $productIds)
            ->groupBy('activation_key_create_history_id')
            ->havingRaw('count(distinct product_id) = ' . count($productIds))
            ->get('activation_key_create_history_id');
    }
}
  • ActivationKeyCreateHistoryController.php (フィルタ部分)
        $grid->filter(function ($filter) {
            $filter->where(function ($query) {
                $aKCreateHistoryProducts = ActivationKeyCreateHistoryProduct::ActivationKeyCreateHistoryProducts($this->input);
                $aKCreateHistoriesIds = [];
                foreach ($aKCreateHistoryProducts as $item) {
                    $aKCreateHistoriesIds[] = $item['activation_key_create_history_id'];
                }

                $query->whereIn('id', $aKCreateHistoriesIds);

            }, 'Products')->multipleSelect(Product::pluck('name', 'id')->toArray());
        });
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?