Support the ongoing development of Laravel.io →
Database Eloquent

Here are my models:

class BookReading extends Eloquent {

    // Book reading has many authors
    public function authors()
    {
        return $this->belongsToMany('Author');
    }
}

class Author extends Eloquent {

    public function book_readings()
    {
        return $this->hasMany('BookReading');
    }
}

This works:

$book_stores = [1,2,3,4];
$book_readings = BookReading::whereIn('location_id', $book_stores)
                    ->first()->authors()->get()->toJson();

This does not work
$book_readings = BookReading::whereIn('location_id', $book_stores)
                    ->get()->authors()->get()->toJson();

Is there a way to get all book readings and associated authors in one query?

Last updated 2 years ago.
0

I figured it out:

$book_readings = BookReading::whereIn('location_id', $book_stores)         
->with('authors')           
 ->get();
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Jameron jameron Joined 16 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.