简体   繁体   中英

how get many record from an array in laravel

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('App\book','categoryb_book');
  }

}

my book model

class book extends Model
{



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

}

my code

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

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
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM