Gagan
Gagan

Reputation: 5656

Advanced nested AND clause in Laravel 5 Eloquent

I am having a hard time converting this query to laravel eloquent and any help will be well appreciated.

The query that I need to run is

SELECT * FROM `articles` WHERE `articles`.`deleted_at` IS NULL AND `id` <> 2 AND (`tags` LIKE '%tag1%' OR `tags` LIKE '%tag2%')

This is what I have now

$relatedArticles = Article::where('id', '<>', $article->id);
if (!is_null($article->tags)) {
    foreach (explode(',', $article->tags) as $tag) {

        $relatedArticles = $relatedArticles->orWhere('tags', 'LIKE', '%' . $tag . '%');
    }
}
$relatedArticles = $relatedArticles->get();

But the above code yields me

SELECT * FROM `articles` WHERE `articles`.`deleted_at` IS NULL AND `id` <> 2 OR `tags` LIKE '%tag1%' OR `tags` LIKE '%tag2%'

which is not what I am looking for.

Thanks

With Regards Gagan

Upvotes: 2

Views: 399

Answers (3)

Stuart Wagner
Stuart Wagner

Reputation: 2067

Try this:

$relatedArticles = Article::where('id', '<>', $article->id);

if (!is_null($article->tags)) {
    $relatedArticles->where(function($query) use ($article)
    {
        foreach (explode(',', $article->tags) as $tag) {
            $query->orWhere('tags', 'LIKE', '%' . $tag . '%');
        }
    });
}

$relatedArticles->get();

More info on advanced wheres.

Upvotes: 0

Karl Casas
Karl Casas

Reputation: 855

You should use "advanced where". Instead of a column name you feed the where with a function. For more clarity look it up here http://laravel.com/docs/5.0/queries#advanced-wheres. Your code should look like the one below:

$relatedArticles = Article::where('id', '<>', $article->id);

if (!is_null($article->tags)) {
    $relatedArticles->where(function($query) use ($article) {
        foreach (explode(',', $article->tags) as $tag) {
            $query->orWhere('tags', 'LIKE', '%' . $tag . '%');
        }
    });
}

$relatedArticles = $relatedArticles->get();

P.S. if you're wondering what use is, anonymous functions on PHP are not like on JavaScript, you need to specify the variables that would be visible on the function.

Upvotes: 1

FBidu
FBidu

Reputation: 1012

Well, it's easy to convert that SQL in a Laravel query using the Query Builder syntax.

It would go like this:

$relatedArticles = Article::where('id', '<>', $article->id)
                            ->where(function($query)
                                   {
                                        $query->where(`tags`, 'like', '%tag1%')
                                              ->orWhere(`tags`, 'like', '%tag2%')
                                   });

More info on that: Laravel Advanced Wheres

Upvotes: 0

Related Questions