fulcrumsecurity's avatar

User > Book > Author | Eloquent Relationship

Hello. I'm working on a project where users keep track of the books they've read. I'm trying to figure out how to retrieve all of the Authors of the books the user has read. How can I set up my models to do this via Eloquent? Here's the database setup:

Users: id

Books: id author_id

Book_User book_id user_id

Authors: id

0 likes
3 replies
RandyMorton's avatar

HY there good morning i can see your post ad i have some suggestion

User Model: Assuming your users table has a primary key column named id, you can define the User model like this:

use Illuminate\Database\Eloquent\Model;

class User extends Model { protected $table = 'users'; https://www.myaarpmedicare.dev/

// Define the relationship to books
public function books()
{
    return $this->belongsToMany(Book::class, 'user_books');
}

// Define the relationship to authors through books
public function authors()
{
    return $this->belongsToMany(Author::class, 'user_books')
        ->join('books', 'authors.id', '=', 'books.author_id')
        ->distinct();
}

}

Thanks and regards RandyMorton

aosdev's avatar

You can see this type of usage at official documantation;

Structure;

projects
    id - integer
    name - string
 
environments
    id - integer
    project_id - integer
    name - string
 
deployments
    id - integer
    environment_id - integer
    commit_hash - string
<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
 
class Project extends Model
{
    /**
     * Get all of the deployments for the project.
     */
    public function deployments(): HasManyThrough
    {
        return $this->hasManyThrough(Deployment::class, Environment::class);
    }
}

ref: https://laravel.com/docs/10.x/eloquent-relationships#has-many-through

Please or to participate in this conversation.