Reputation: 186
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
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
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