php - For loop with two database queries in Twig

608

I'd really love if anyone can help, I'm trying to figure out a way to loop through two queries in Twig. I can create it in PHP but I'm having doing the same thing on Twig. This is how I'd normally do it on PHP:

foreach($items as $item){
   $product_id = $item;
   $products = $app->db->table('products')->where('id', $product_id)->first();
   echo "<li>" . $products->title . "</li>";
}

The above code will work fine but on Twig it will not loop to the next loop, but it will keep on looping the same thing. Kindly help if you know how I can use Twig for loop like I use it above. I'm querying it using Laravel Eloquent in Slim.

This is what I did:

The controller

$products = $app->db->table('products')->where('trash', '0')->first();

The View

{% for item in items %}
      {% set product_id = item.id %}
       <li> {{ products.title }}</li>
{% endfor %} 

It will only show the first row and repeat the samething.

679

Answer

Solution:

Don't attempt to run queries from a template. Do it in the controller and pass the result to the template.

Also$items appears to be an array of IDs, so you should be able to load all of the products at once with a where-in condition (instead of multiple queries):

Controller:

$products = $app->db->table('products')->whereIn('id', $items)->get();

// pass $products to the template as "products"

Twig template:

{% for product in products %}
    <li>{{ product.title }}</li>
{% endfor %}

People are also looking for solutions to the problem: continuous integration - How to enable PHP redis extension on Travis

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.