Remember to remove spaces from each element in your $meta_keywords array. Just run trim(). Not sure if that's the problem here but it could definitively affect your results.
May 22, 2019
8
Level 1
Using whereIn and comma separated values
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!
Level 122
$terms = explode(',',$post->meta_keywords);
$query = Post::where('category_id','=',$post->category_id)
->where('status','=','PUBLISHED')
->where('id','!=',$post->id)
->where(function($query) use($terms) {
foreach($terms as $term) {
$query->orWhere('meta_keywords', 'like', "%$term%");
};
})
->inRandomOrder()
->take(3)
->get();
1 like
Please or to participate in this conversation.