PyroCMS(Laravel) where clause within the translations not working correctly

114 Views Asked by At

I have been struggling with this for quite a while. I use PyroCMS and it has a Posts module that has all the fields in the database and all that and if you want to find a specific post, you can just use a normal WHERE clause and find a post by a date and so on.

But if a field is checked in CMS as translatable, I can't access that field and use it to find a post, because the CMS creates another field in another table that is called posts_translations, and it contains all the fields that are translatable. Usually that is a simple $posts->where("field","value"), but the field doesn't exist if it's translatable.

So I tried to use whereHas, but it doesn't really return anything.

public function meklet(PostRepositoryInterface $posts, $q)
{
    $postss = $posts->all()->whereHas('translations', function($query) use($q) {
        $query = $query->where(function($query) use($q) {
            $query->where('title', 'like', '%'.$q.'%');
        });
    });
    die(var_dump($q));
    return $this->view->make("mendo.module.report::reports/search");
}

As you can see I use PostRepositoryInterface maybe I need to use some other class to access what I want? Im very confused, I know its a laravel base, but I can't really wrap my head around this simple problem.

1

There are 1 best solutions below

0
Piterden On

You shouldn't use one letter variables and too much nested functions there:

/**
 * Searches for all matches.
 *
 * @param   PostRepositoryInterface  $posts   The posts
 * @param   string                   $search  The search
 * @return  View
 */
public function search(PostRepositoryInterface $posts, $search)
{
    /* @var PostCollection $results */
    $results = $posts->all()->filter(
        function (PostInterface $post) use ($search) {
            return str_contains(
                strtolower($post->getFieldValue('title')),
                strtolower($search)
            );
        }
    );

    dd($results);

    return $this->view->make('mendo.module.report::reports/search', [
        'posts' => $results,
    ]);
}

And route should be like:

    'posts/search/{search}'               => [
        'as'   => 'anomaly.module.posts::posts.search',
        'uses' => 'Anomaly\PostsModule\Http\Controller\PostsController@search',
    ],

To use a DB query directly you need to write translations join self. It is not so difficult.