0

I want to get all the books under a certain category. The category has many subjects and books are linked to subjects.

My code:

class BookCategory extends Model {

    public function subjects() {
        return $this->hasMany('BookSubject', 'category_id', 'id');
    }

    public function getBooksAttribute() {
        return Books::whereHas('subjects', function ($query) {
            return $query->join('book_category', 'book_category.id', '=', 'book_subject.subject_id')
                         ->where('book_category.id', $this->id);
        })->get();
    }
}

and my Books model:

class Books extends Model {

    public function subjects() {
        return $this->belongsToMany('BookSubject', 'book_by_subject', 'book_id', 'subject_id');
    }
}

If I do:

$cats = \App\Models\BookCategory::all();
foreach ($cats as $c) {
    echo $c->books->count();
}

It's always returning 0 for all the rows. What I'm I doing wrong?

1 Answer 1

1

I believe the problem is in your subquery:

return $query->join('book_category', 'book_category.id', '=', 'book_subject.subject_id')
                     ->where('book_category.id', $this->id);

I'm pretty sure book_subject.subject_id should be book_subject.category_id

Hard to tell without seeing your db schema.

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

2 Comments

Hahah . I feel so dumb and studid now . Thanks buddy @Pitchinnate
No problem we all have done the same type of thing a hundred times.

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.