Maybe I am doing this incorrectly, however what I want to do logically is this:
I want to first select all posts that contain a certain string.
Then from those results, I want to narrow it down to only posts within a certain date (Y|m|d).
So this is what im doing at the moment:
$results = DB::table('posts');
if ($query == null){
$query = "Posted On: " . $date;
}else {
$results->where('posts.title', 'LIKE', "%$query%")
->orWhere('posts.meta_description', 'LIKE', "%$query%")
->orWhere('posts.meta_keywords', 'LIKE', "%$query%")
->orWhere('posts.body', 'LIKE', "%$query%")
->orWhere('posts.seo_title', 'LIKE', "%$query%");
$query = $query." / Posted On: " . $date;
}
$results->where(function($query) use ($date){
$date = explode('-', $date);
if (!isset($date[1])){
$query->whereYear('created_at', '=', $date[0]);
}else if(isset($date[1]) && !isset($date[2])){
$query->whereYear('created_at', '=', $date[0])
->whereMonth('created_at', '=', $date[1]);
}else if (isset($date[1]) && isset($date[2])){
$query->whereYear('created_at', '=', $date[0])
->whereMonth('created_at', '=', $date[1])
->whereDay('created_at', '=', $date[2]);
}
});
$results = $results->paginate($this->paginate_size());
However, this query is still just returning anything that contains the query string and ignoring the fact that I want to select a subset that are only posts on a specific year/month/day.
What am I missing?
Edit:
Using $results->toSql(); I get the query:
select * from `posts` where `posts`.`title` LIKE ? or
`posts`.`meta_description` LIKE ? or `posts`.`meta_keywords` LIKE ? or
`posts`.`body` LIKE ? or `posts`.`seo_title` LIKE ? and year(`created_at`) = ?
However, it is not working...
If I enter for example the query "Lorem" it will find all of the posts with the text Lorem in it.
However, when I add a specific date like just "2015", it should not show ANY posts from 2015 with the query Lorem since it does not exist.
So there is some logic problem here. Any ideas?
$resultsto the value returned by the where function. So$results = $results->where(...select * fromposts` whereposts.titleLIKE ? orposts.meta_descriptionLIKE ? orposts.meta_keywordsLIKE ? orposts.bodyLIKE ? orposts.seo_titleLIKE ? and year(created_at) = ? `