Search code examples
phpsqllaravellaravel-query-builder

Laravel chainable where clause is not working


i have blogs table in the DB which has tag,tag1,tag2 columns, i'm trying to get all the blogs related to current blog in the show page if any of the 3 tags are similar to it , i'm using the code below but the problem is that i'm getting the main blog with related which i don't want. i'm using where not but its not working


function blogShow($id) {
        
        $blog = Blog::find($id);

        $tags = [$blog->tag,$blog->tag1,$blog->tag2];

        $related = Blog::select("*")
        ->where('id', '!=', $id)
        ->whereIn('tag',$tags)
        ->orWhereIn('tag1',$tags)
        ->orWhereIn('tag2',$tags)
        ->get();

        return view('main.blogs.show',compact('blog','related'));
    }

PS: when i use -> toSql i'm getting the current query : "select * from blogs where id != ? and tag in (?, ?, ?) or tag1 in (?, ?, ?) or tag2 in (?, ?, ?)" which seems correct ,the $id value is correct as well so where is the problem .


Solution

  • You should make subcondition like this

    function blogShow($id) {
        
        $blog = Blog::find($id);
    
        $tags = [$blog->tag,$blog->tag1,$blog->tag2];
    
        $related = Blog::select("*")
        ->where('id', '!=', $id)
        ->where(function($q) {
          $q->whereIn('tag',$tags)
            ->orWhereIn('tag1',$tags)
            ->orWhereIn('tag2',$tags);
        })
        ->get();
    
        return view('main.blogs.show',compact('blog','related'));
    }
    

    However, I highly recommend that you use the nicer way for tags. for example you can create a tags table and create a relation table blog_tag with blog_id and tag_id so you have unlimited tags and excluding duplicate tags