In Laravel, I have two tables:
books table has two fields( id , name )
users has three fields( id , name, book_id )
How I can get users that read more than five books?
You can't as what you show us is one-to-many relationship, where many User
belong to one Book
. That being said, one user can have only one book related. What you want is probably many-to-many relationship with pivot table, like this:
users table: id, name
book_user pivot table: book_id, user_id
books table: id, name
// then relationships:
// User model
public function books()
{
return $this->belongsToMany('Book');
}
// Book model
public function users()
{
return $this->belongsToMany('User');
}
// and calling relations:
$user = User::first();
$user->books; // collection of Book models
// Now to fetch users that have more than 5 books related, what you asked:
User::has('books', '>', 5)->get(); // collection of User models