【发布时间】:2014-06-22 00:01:58
【问题描述】:
在 Laravel 中,我有两个表:
books 表有两个字段( id , name )
users 有三个字段(id、name、book_id)
如何让用户阅读超过五本书?
【问题讨论】:
标签: mysql orm eloquent database-relations
在 Laravel 中,我有两个表:
books 表有两个字段( id , name )
users 有三个字段(id、name、book_id)
如何让用户阅读超过五本书?
【问题讨论】:
标签: mysql orm eloquent database-relations
您不能因为您向我们展示的是一对多关系,其中许多 User 属于一个 Book。话虽如此,一个用户只能拥有一本书相关。您想要的可能是与数据透视表的多对多关系,如下所示:
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
【讨论】: