Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GroundZero's avatar

Query with dynamic amount of joins

Ha guys,

I have a unknown (1 up to 4) amount of joins that I would like to add to my query. Unfortunately, no matter what I do, the query ignores my join. No error, nothing. Can someone please help me out and tell me how to get this working?

// create a new query object
$products = new Products;

// create selects and joins
foreach($fields as $field){
    switch($field){
        case 'ProductNumber':
            $select[] = 'ProductNumber';
        break;

        case 'EAN':
            $select[] = 'EAN';
        break;

        case 'caseCode':
            $select[] = 'xxxColorID';
        break;

        case 'diameterCase':
            $select[] = 'Diameter';
        break;

        case 'straightxxx':
            $select[] = 'xxxMount';
        break;

        case 'xxxFamily':
                $products->join('xxxLinking', 'Products.id', '=', 'xxxLinking.xxxProductId', 'inner');
            $joins[] = 'xxxLinking';
        break;

        case 'diameterxxx':
            $products->join('Products', 'Products.id', '=', 'xxxLinking.xxxProductId', 'innert');
            $joins[] = 'Products';
        break;

    }
}




DB::connection()->enableQueryLog();

$products->select($select)->limit(1)->get();
$products->join('a', 'a.a', '=', 'b.b', 'inner');

$queries = DB::getQueryLog();

echo '<pre><code>'.print_r($queries, true).'</code></pre>';
echo '<pre><code>'.print_r($products[0], true).'</code></pre>';
echo '<pre><code>'.print_r($select, true).'</code></pre>';
echo '<pre><code>'.print_r($joins, true).'</code></pre>';

the select is working properly obvious, but the JOINS are just totally ignored.

Hope someone can help me out!

Best regards

0 likes
2 replies
TerrePorter's avatar
Level 12

The only way I could get the joins to work was to change

$products = new Products;

to 

$products = Products::select();

also, you have a type on the diameterxxx join - innert vs inner

hope that helps

GroundZero's avatar

Thanks for your answer. I will look into that :)

Please or to participate in this conversation.