【问题标题】:Laravel Nova Filter using joined tableLaravel Nova 过滤器使用连接表
【发布时间】:2021-06-18 11:00:09
【问题描述】:

我正在尝试根据来自两个不同表的数据为我的模型“问题”构建一个 Laravel Nova 过滤器。我已经弄清楚了我需要使用的确切 SQL 查询,但无法弄清楚如何在 Nova 过滤器的 apply() 方法中使用它

表“问题”列: id, ...

表格“主题”列: id, question_id, theme_id

我正在尝试使用的 SQL 查询:

SELECT questions.*
From questions
Inner JOIN themes on questions.id=themes.question_id
WHERE themes.theme_id = 3 (value taken from the Nova Filter options)

我在 Laravel Nova QuestionsThemeFilter.php 中的过滤器:

class QuestionsThemeFilter extends BooleanFilter
{
    public $name = 'filter by theme';

    public function apply(Request $request, $query, $value) {
        // This is what I'm missing...
    }

    public function options(Request $request) {
        $themes = Themes::all();
        $themesArray = array();
        foreach($themes as $item) {
           $themesArray[$item['title']] = strval($item['id']);
        }
        return $themesArray;
    }
}

那么,我该怎么做呢?

其他问题:由于我是 Laravel 的初学者,我应该如何开始调试呢?使用 dd() 不起作用(过滤器刚刚中断),我不知道如何调试它。有没有办法从 apply 方法中转储一些值(例如 $value)?

提前感谢您的帮助,非常感谢:-D

【问题讨论】:

    标签: php laravel laravel-nova


    【解决方案1】:

    查看代码中的cmets

    use Illuminate\Support\Arr;
    use Illuminate\Support\Facades\Log;
    
    class QuestionsThemeFilter extends BooleanFilter
    {
        public function apply(Request $request, $query, $value) {
            // Since you are using BooleanFilter $value will be an associate array with true/false value
            $selectedThemes = Arr::where($value, function ($v, $k) {
                return $v === true;
            });
            $selectedThemeIds = array_keys($selectedThemes)
    
            // For debugging print some logs and check
            Log::info($value)
            Log::info($selectedThemeIds);
            
            return $query->join('themes', 'questions.id', '=', 'themes.question_id')
                  ->whereIn('themes.theme_id', $selectedThemeIds);
    
            // If you are using normal filter then below code will be enough
            /*            
            return $query->join('themes', 'questions.id', '=', 'themes.question_id')
                  ->where('themes.theme_id', $value);
            */
        }
    
        public function options(Request $request) {
            // You can use Laravel collection method pluck
            return Themes::pluck('id', 'title')->all();
        }
    }
    

    参考资料:

    Pluck

    Boolean Filter

    Arr::where

    【讨论】:

    • 非常感谢!!!这对我有很大帮助!我明天测试一下。
    • 这非常有效。我不得不稍微调整一下,但这是完美的解决方案。感谢您提供有关日志系统的信息,我不知道。完美回复,再次感谢!
    猜你喜欢
    • 2021-01-26
    • 2019-03-28
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多