Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent
Last updated 2 years ago.
0

You just have to put the loop inside the closure (the function with the $subQuery). And since inside the closure PHP doesn't know the $accountTypes variable you need to have a use statement in the closure too.

$query->where(function ($subQuery) use ($accountTypes) {

    foreach ($accountTypes as $accountType) {
        $subQuery->orWhere('account_type', $accountType);
    }

}

Haven't tested it but that should point you in the right direction :)

0

Thanks ftiersch. That looks like it'll work. I'll know for sure once I test it.

0

So I finally tested this and it seems it doesn't work. I'm guessing the subquery considers the $accountTypes variable as a new variable because I get the error "Invalid argument supplied for foreach()".

Anyone know how to solve this?

0

/bump

This is my full function.

/**
     * Fetch dealer id from the database
     *
     * @param $dealerIdInFeed
     * @param $accountTypes
     * @return mixed
     */
    public function fetchDealerId($dealerIdInFeed, $accountTypes)
    {
        $dealer = $this->dealer->where('foreign_dealer_id', $dealerIdInFeed)
            ->where(function ($subQuery) use ($accountTypes) {
                foreach($accountTypes as $accountType)
                {
                    $subQuery->orWhere('account_type', $accountType);
                }
            })
            ->get();

        return $dealer->id;
    }
0

I figured out the problem. There are instances when the array passed to the function only has 1 item in it. Updated function below:

public function fetchDealerId($dealerIdInFeed, $accountTypes)
    {
        $dealer = $this->dealer->where('foreign_dealer_id', $dealerIdInFeed)
            ->where(function ($subQuery) use ($accountTypes) {
                if(count($accountTypes) > 1)
                {
                    foreach($accountTypes as $accountType)
                    {
                        $subQuery->orWhere('account_type', $accountType);
                    }
                }
                else
                {
                    $subQuery->orWhere('account_type', $accountTypes);
                }
            })
            ->first();

        if($dealer != null)
            return $dealer->id;

        return null;
    }
0

Sign in to participate in this thread!

Eventy

Your banner here too?

VenomRush venomrush Joined 27 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.