skip to Main Content

I have an array of category , and this categories have many books (belongToMany) how i can get all book

sorry about my English

category model

class category_b extends Model
{
    protected $table = 'categoryb';
    protected $attributes = array(
        'lang'=> 'fa',
    );

  public function getBooks()
  {
      return $this->belongsToMany('Appbook','categoryb_book');
  }

}

my book model

class book extends Model
{



    public function getCategory()
    {
        return $this->belongsToMany('Appcategory_b','categoryb_book');
    }

}

my code

$Category = $user->subscriptions(category_b::class)->pluck('id');
$bookCategory= category_b::whereIn('id',$Category)->get();
$bookCategory = $bookCategory->getBooks;

2

Answers


  1. You can use a foreach as mentioned in the docs to iterate through the books of you’re fetched category.

    foreach ($bookCategory as $book) {
     //access book's attributes
    }
    

    Or likewise you can get the categories of a certain book.

    $book = Book::find($id);
    $categories = $book->getCategory();
    foreach ($categories as $category) {
     //access category's attributes
    }
    
    Login or Signup to reply.
  2. As @Makdous indicated, different approaches exist, you may take the one that fits your need.

    Notice that the loop approach may lead to duplicate books, so after the loop you will have to delete duplicate records.

    To avoid that problem, one solution would be to query the Book model directly:

    $categoryIds = $user->subscriptions(category_b::class)->pluck('id');
    
    $books = book::whereHas('getCategory', function ($q) use ($categoryIds) {
        return $q->whereIn('categoryb.id', $categoryIds);
    })
    ->get();
    

    EDIT:

    You may go beyond that and improve the readability of your code by defining a local scope.

    In your Book class:

    class book extends Model 
    {
        // .....
        // .....
    
    
        // Somewhere in your Book class ...
    
        public function scopeOfCategories($query, $categoryIds = [])
        {
            return $query->whereHas('getCategory', function ($q) use 
                ($categoryIds) {
                return $q->whereIn('categoryb.id', $categoryIds);
            });
        }
    
    }
    

    Now you can replace the old code snippet with the following:

    $categoryIds = $user->subscriptions(category_b::class)->pluck('id');
    
    $books = book::ofCategories($categoryIds)->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search