0

I have two tables:

LECTURES
id   name
1 - Lesson 1
2 - Lesson 2
3 - Lesson 3

LECTURESTYPE
id  id_lectures   numb
1 -     1 -        10
2 -     2 -        20
3 -     1 -        30

How can I sum numbs column for each lesson and take result like : name: Lesson 1 numb: 40

I want to display the sum of numb for each lesson.

3 Answers 3

0

Try LECTURESTYPE::with('lectures')->sum('numb')->GroupBy('id_lectures')->get()

Sign up to request clarification or add additional context in comments.

3 Comments

what realtionship i need to put in models
For LECTURESTYPE model : public function lectures(){ return $this->hasMany('App\LECTURES','id_lectures'); }
Call to a member function groupBy() on double
0

You need the following relation:

Lecture (App\Lecture.php)

namespace App;
class Lecture extends Model {
    protected $table = 'lectures';
    public function lecturetype() {
        return $this->hasMany('App\LectureType');
    }
}

LectureType (App\LectureType.php)

namespace App;
class LectureType extends Model {
    protected $table = 'lecturestype';
    public function lecture() {
        return $this->belongsTo('App\Lecture');
    }
}

Now you can try in the Controller:

$sum = App\LectureType::with('lecture')->GroupBy('id_lectures')->sum('numb');

2 Comments

$sum = App\LectureType::with('lecture')->GroupBy('id_lectures')->sum('numb');
only back to me number 10 no array
0

Try LECTURESTYPE::with('lectures')->GroupBy('id_lectures')->sum('numb')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.