malesandro
4 months ago

Using whereIn and comma separated values

Posted 4 months ago by malesandro

Hi everyone. I am building a related posts block. In the posts table, I have a column called meta_keywords, which holds a string with comma separated values:

meta_keywords = "earth, wind, fire"

I want to get related posts, based on the meta_keywords column.

My way of going at this is as follows:

//get the meta_keywords from a single post
$meta_keywords = explode(',',$post->meta_keywords);
//get posts that match the criteria plus have some of the meta_keywords
$relatedPosts = Post::where('category_id','=',$post->category_id)
                            ->where('status','=','PUBLISHED')
                            ->where('id','!=',$post->id)
                            ->whereIn('meta_keywords',$meta_keywords)
                            ->inRandomOrder()
                            ->take(3)->get();

Other posts in the same category, have the following meta_keywords:

"wood, stone, earth"
"water, fire, earth"
"water, wood, grass"

However I am not getting any results for this query. Can anyone please help me? Thanks!

Please sign in or create an account to participate in this conversation.