Pinchanzee's avatar

Where condition has no effect on Relation

I have a HasMany relation from EntityType model to the Entity model (1 Entity Type has many Entities). I'm trying to create a livewire component with wire:model.live="nameFilter", but it's completely ignoring my LIKE condition. Even when I try the filter directly -without the when- it doesn't work.

The second query inside the IF loop does work as intended, however, I understood the HasMany structure as the correct way to consistently retrieve and filter linked models.

In the following example, I have 12 records for the project and 1 of them matches the nameFilter LIKE.

$entities = $this->entityType->entities->where('project_id', $this->project->id)
    ->when($this->nameFilter, function($query) {
        $query->where('name', 'like', '%'.$this->nameFilter.'%');
    });

if ($this->nameFilter) {
    // echo $entities->count(); // 12, incorrect, as if the like as not been applied
    $entities = Entity::where('entity_type_id', $this->entityType->id)
        ->where('project_id', $this->project->id)
        ->where('name', 'like', '%'.$this->nameFilter.'%')
        ->get();
        // echo $entities->count(); // 1, correct, the one record that matches the name filter (in this case)
}

What fundamentals am I misunderstanding for my first approach to just not work at all?

0 likes
2 replies

Please or to participate in this conversation.