Вопрос

I have the following requirements:

  • a User can add a Book to a Collection
  • the Collection has different types (perhaps Models): Wishlist, Watchlist, Favoritelist
  • Book can be part of multiple Collection types (e.g. can be in Wishlist and Watchlist)

Thus, the Models I have so far are: User and Book

I'd like to access the relationships in a very easy way, e.g.

$wishlist = $user->collections()->wishlist;
$watchlist = $user->collections()->watchlist;

These two variables should then hold a collection of Books.


I'd also like to access the different collections in a way that I can count how many times a certain Book is part of any User's Wishlist. E.g.

$book = Book::find(1);
$wishlist_count = $book->collections()->wishlist->count();


How do I go about modeling these relationships?

Это было полезно?

Решение

Setup pivot table for every type:

// You can call the relations pretty easily:
$user->booksWishlist; // collection of Book models

$book->usersWatchlist->count(); // get count on the Collection of User models
// or alternatively
$book->usersWatchlist()->count(); // get count() on SQL query on related users


// tables:
book_user_wishlist: user_id, book_id, .. (id, timestamps and whatever you need)
book_user_watchlist: user_id, book_id, .. (id, timestamps and whatever you need)
// and so on..

// --- Relations ---
// User model
public function booksWatchlist()
{
    return $this->belongsToMany('Book', 'book_user_watchlist'); 
}

public function booksWishlist()
{
    return $this->belongsToMany('Book', 'book_user_wishlist'); 
}

// Book model
public function usersWatchlist()
{
    return $this->belongsToMany('User', 'book_user_watchlist'); 
}

public function usersWishlist()
{
    return $this->belongsToMany('User', 'book_user_wishlist'); 
}

If you need even more power on the ..list models you can setup custom pivot models for every list overriding newPivot() method on User and Book models.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top