【问题标题】:Eloquent ORM Laravel relations雄辩的 ORM Laravel 关系
【发布时间】:2014-06-22 00:01:58
【问题描述】:

在 Laravel 中,我有两个表:

books 表有两个字段( id , name )

users 有三个字段(idnamebook_id

如何让用户阅读超过五本书?

【问题讨论】:

    标签: mysql orm eloquent database-relations


    【解决方案1】:

    您不能因为您向我们展示的是一对多关系,其中许多 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2016-02-26
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 2018-11-28
      相关资源
      最近更新 更多