Domanda

I have two tables {users, books} . How can I make join with laravel between them to get count of books read?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top