XF 2.2 Help with a query

Lee

Well-known member
I have a basic query that I am running in a widget:

PHP:
    public function render()
    {
        if(!\XF::visitor()->hasPermission('thoughts', 'viewOwn'))
        {
            return false;
        }

        $thoughtsFinder = $this->finder('TLS\Thoughts:Thought')
                    ->order('post_date', 'desc')
                    ->limit(10);

        if(!\XF::visitor()->hasPermission('thoughts', 'viewAll'))
        {
            $thoughtsFinder->where('user_id', \XF::visitor()->user_id);     
        }

        $viewParams = [
            'thoughts' => $thoughtsFinder->fetch(),
        ];
        return $this->renderer('tls_widget_new_thoughts', $viewParams);
    }

This works well and gets 10 results as expected.

What I would like to do is look at the field is_private in the table and filter results based on if that is true or not, but with conditions.

If a user has permission to view all, get get all entries as above, unless the is_private column is 1. Unless, that record belongs to the owner, then get it anyway.

If a user has the permission viewPrivate then get all entries regardless of the is_private column value.

What is the best way to achieve this please..? :)
 
This seems like it should be relatively easy to achieve, but I have spent a couple of hours trying different things and scratching my head.

As a side note, anything I do try seems to deducted the rows from the results rather than return the full 10 results.
 
I fixed this as shown here:

PHP:
public function render()
    {
        if(!\XF::visitor()->hasPermission('thoughts', 'viewOwn'))
        {
            return '';
        }

        if(\XF::visitor()->hasPermission('thoughts', 'canViewPrivate'))
        {
            $thoughtsFinder = $this->finder('TLS\Thoughts:Thought')
                        ->order('post_date', 'desc')
                        ->limit(10);

            if(!\XF::visitor()->hasPermission('thoughts', 'viewAll'))
            {
                $thoughtsFinder->where('user_id', \XF::visitor()->user_id);       
            }
        }
        else
        {
            $thoughtsFinder = $this->finder('TLS\Thoughts:Thought')
                        ->order('post_date', 'desc')
                        ->whereOr(['is_private', '<', 1],
                        ['user_id', \XF::visitor()->user_id])
                        ->limit(10);

            if(!\XF::visitor()->hasPermission('thoughts', 'viewAll'))
            {
                $thoughtsFinder->where('user_id', \XF::visitor()->user_id);       
            }           
        }


        $viewParams = [
            'thoughts' => $thoughtsFinder->fetch(),
        ];
        return $this->renderer('tls_widget_new_thoughts', $viewParams);
    }

Should I be storing these functions in a repository or a service or something so that I can use them in multiple places...?
 
Top Bottom