简体   繁体   中英

Where clause not filtering

In my model I have the following two functions:

public function Children()
{
    return $this->hasMany(Menu::class, 'parent_menu_id', 'id');
}

public function ActiveChildren()
{
    $securityLevel = Auth()->User()->security_level_id;
    $activeChildren = Menu::Children()
        ->where('active_', TRUE)
        ->where('security_level_id', $securityLevel);

    return $activeChildren;
}

Children() returns a list of all Menu items where their parent_menu_id matches the id of this record. This is used in Nova for setup purposes.

With ActiveChildren() I am trying to create a filtered list of items for the actual menu where active_ = TRUE and security_level_id = security level id of the current user.

But instead, ActiveChildren() returns all menu items instead of the filtered set. ActiveChildren populates an array in the following static function:

public static function Tree()
{
    return static::with(implode('.', array_fill(0, 4, 'ActiveChildren')))
        ->where('menu_type', '=', 'PRT')
        ->get();
}

That is then loaded via the AppServiceProvider whenever the menu is included in a blade file:

public function boot()
{
    view()->composer('desktop.menu.parent', function ($view) {
        $items = Menu::Tree();
        $view->withItems($items);
    });
}

All this works fine, just the menu items are not filtered, any ideas?

It looks like you need to update your ActiveChildren() relation:

public function ActiveChildren()
{
    $securityLevel = Auth()->User()->security_level_id;

    /* $activeChildren = Menu::Children()
     *     ->where('active_', TRUE)
     *     ->where('security_level_id', $securityLevel);
     *
     * return $activeChildren;
     */
    return $this->Children() // switch Menu::Children() to $this->Children()
        ->where('active_', TRUE)
        ->where('security_level_id', $securityLevel);
}

尝试这个:

\App\model_name::where('active_',TRUE)->where('security_level_id', $securityLevel);

After some more investigation, I have found the issue to be in my blade code.

I still referenced $item['children'] instead of $item['activechildren']

<li>{{ $item['menu_text'] }}</li>
@if (count($item['activechildren']) > 0)
    <ul>
    @foreach($item['activechildren'] as $item)
        @include('desktop.menu.children', $item)
    @endforeach
    </ul>
@endif

Why did $item['children'] still work? Why wasn't this throwing an error?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM