1

I use Laravel and Eloquent and I want get data from two table via relation.

For example i want select all book in categories that category status is active.

class Book extends Model
{
    public $belongsTo  = [
        'category' => '..\Models\Categories',
    ];

    public function categories() {
        return $this->belongsTo('..\Models\Categories');
    }

}

In controller i can use next code for select all books.

Book::with('categories');

Is there way to select all book in categories that category status is active?

3
  • Can you make it clear, if book can belong to multiple categories or single category? Commented Sep 2, 2019 at 5:56
  • book can belong to multiple categories Commented Sep 2, 2019 at 5:58
  • then definitely, you have a many-to-many relationship and not one-to-many . Commented Sep 2, 2019 at 6:00

2 Answers 2

1

You can use eager loading for this.

Book::with(['categories' => function($query){
    $query->where('status','active');
}]);
Sign up to request clarification or add additional context in comments.

Comments

0
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * The categories that associated with the book.
     */
    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

In category model you can define scope

like public function scopeStatus($query, $status='active') { $query->where('staatus', $status); }

and you can retrieve as $book->categories and reverse is $category->books and categories with books Category::with('books')->status('active')->get() .

Note: you need pivot table in this situation

1 Comment

@aya I have edited my answer, you can try this and let me know, if you are facing any issue with it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.