Answer the question
In order to leave comments, you need to log in
Selecting relationships with JOIN in Laravel 4.2?
I am using Laravel 4.2.
I'm fetching a user's article count with a JOIN like this:
User::join('pages as articles', 'articles.user_id', '=', 'users.id', 'left outer')->select([DB::raw('users.*, count(articles.id) as articlesCount')])->get()
public function publishedArticles()
{
return $this->hasMany('Page', 'user_id')->whereType(Page::TYPE_ARTICLE)
->whereIsPublished(1)
->where('published_at', '<', date('Y-m-d H:i:s'));
}
public function publishedQuestions()
{
return $this->hasMany('Page', 'user_id')->whereType(Page::TYPE_QUESTION)
->whereIsPublished(1)
->where('published_at', '<', date('Y-m-d H:i:s'));
}
Answer the question
In order to leave comments, you need to log in
And why do you need to write a request at all? Use links between models, get a collection with posts from the link, it has a count method. It doesn't get easier.
Ok, now look, I'm giving you examples directly from the official tutorial
$user = App\User::find(1);
$user->posts()->where('active', 1)->get();
// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();
// Retrieve all posts that have three or more comments...
$posts = Post::has('comments', '>=', 3)->get();
// Retrieve all posts that have at least one comment with votes...
$posts = Post::has('comments.votes')->get();
// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question