Caner
Caner

Reputation: 186

How to use in laravel 5.4 local scope in a relation call?

I use in my project laravel 5.4 and have 2 models, first model is Group and second model ist Ticket.

In model Group I have following relation:

public function tickets() {
 return $this->hasMany('App\Models\Ticket', 'group_id');
}

In table tickets (model Ticket) I have a bool field called "open", and the local scope:

public function scopeOpen($query) {
   return $query->where('open', 1);
}

How can I filter now by using this relation like: $group->tickets->open, do I have

Upvotes: 2

Views: 727

Answers (3)

Mozammil
Mozammil

Reputation: 8750

You can define a relation as such:

public function ticketsOpen()
{
   return $this->tickets()->open();
}

and then use it as follows:

$group->ticketsOpen;

Upvotes: 2

Sandeesh
Sandeesh

Reputation: 11906

A few ways you can do this.

Add this relation to the Group model

public function openTickets()
{
    return $this->tickets()->open();
}

Access the open tickets like so

$group->openTickets

Or filter the tickets when fetching the results.

$group = Group::with(['tickets' => function ($query) {
    $query->open();
}])->get();

Accessed tickets will have the open scope applied.

$group->tickets

Upvotes: 1

Bara' ayyash
Bara' ayyash

Reputation: 1935

try this :

Group::with('tickets')->open()->get();

Upvotes: 0

Related Questions