skip to Main Content

I have tables called event and eventinfo. Where the event hasMany eventinfo.
I am trying to get the event that has eventinfo with active=1, but it get all the eventinfo whether active is 0 or 1.

   $eventsInfo = Event::find($eventId)
                ->whereHas('EventInfo', function (Builder $query) {
                           $query->where('active', 1);
                 });

can anyone point me where is the issue?

2

Answers


  1. If you want to filter EventInfo that’s loaded, you should use the with function with a closure to apply conditions to the eager loaded models.

    $event = Event::whereHas('EventInfo', function (Builder $query) {
        $query->where('active', 1);
    })->with(['EventInfo' => function ($query) {
        $query->where('active', 1);
    }])->find($eventId);
    
    Login or Signup to reply.
  2. In the code in question, just write find() after whereHas(), so that you can get the Event with EventInfo active=1.

    $eventsInfo = Event::whereHas('EventInfo', function (Builder $query) {
        $query->where('active', 1);
    })
                       ->find($eventId);
    

    P.S.

    If it still doesn’t work, please use toSql() to print out the SQL query statement to check.

    dd(
        Event::whereHas('EventInfo', function (Builder $query) {
            $query->where('active', 1);
        })
             ->where('id', $eventId)
             ->toSql()
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search