S
S
Sergey Sergeev2015-05-10 11:20:50
Laravel
Sergey Sergeev, 2015-05-10 11:20:50

How to create a request in Laravel?

Good afternoon, there are 2 tables p
1. - tasks
- id
- name
2. comments
- id
- task_id
- comments
I need to add the number of comments to the first table, now I'm doing this, but I don't know how to calculate, tell me.

DB::table('tasks')
            ->leftJoin('comments','comments.task_id', '=', 'tasks.id')
            ->select('tasks.*','comments.id as comments_id' )
            ->groupBy('tasks.id')
            ->get();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DieZz, 2015-05-10
@DieZz

Is it important to make a query constructor?
When using Eloquent, I would do this
. In the Task model, we write the connection with the Comments model

public function comments()
{
    return $this->hasMany('App\Comments');
}

In the place where you need to count the number of comments
If you need to get the number of comments for all tasks, you can do this:
$count = 0;
foreach(Task::All() as $task)
{
  $count += $task->comments()->count();
}

S
Shaks, 2015-05-10
@shaks

I have never worked with Laravel, but just looking at your code, you need to use model relationships.
laravel.com/docs/5.0/eloquent#relationships

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question