aya
aya

Reputation: 1613

Laravel Eloquent : get data and use condition for related table column

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?

Upvotes: 1

Views: 2508

Answers (2)

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9693

<?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

Upvotes: 0

Suraj Singh
Suraj Singh

Reputation: 142

You can use eager loading for this.

Book::with(['categories' => function($query){
    $query->where('status','active');
}]);

Upvotes: 1

Related Questions