Reputation: 181
I have two tables {users, books}
.
How can I make join with laravel
between them to get count of books read?
Upvotes: 0
Views: 100
Reputation: 41
Assuming you use Eloquent and your models are called Book and User with a Many-to-Many relationship between them, you could do something like:
Book::has(users)->count();
This will give you the count of all books which have at least one user associated. It will be converted to an inner join internally.
Upvotes: 0
Reputation: 60048
With relationships:
class User extends Eloquent
{
public function books()
{
return $this->hasMany('Book');
}
}
class Book extends Eloquent
{
public function user()
{
return $this->belongsTo('User');
}
}
Then in your code
$user = User::find(1);
$user->books->count();
Upvotes: 1