• Catch one value with xpdo [SOLVED]#

  • Bingo Reply #1, 4 months, 2 weeks ago

    Reply
    I am completely new to xpdo so I'm sorry if it's a stupid question.

    I try to capture only one value in my database. I have solved it using the code below, but realizes that it must be possible to solve without foreach. But how?
    The value in alias is always unique and I just want the id back.

    $output = '';
    
    $query = $modx->newQuery('Product');
    $query->select($modx->getSelectColumns('Product','Product','',array('id')));
    $query->where(array(
       'alias' => 'PRODUCT-NAME',
    ));
    $products = $modx->getCollection('Product',$query);
    
    foreach ($products as $product) {
      
      $output = $product->get('id');
      
    }
    
    return $output;
    


  • opengeek Reply #2, 4 months, 2 weeks ago

    Reply
    Here is one way, using the new getValue() method...

    <?php
    $output = '';
     
    $query = $modx->newQuery('Product');
    $query->select($modx->getSelectColumns('Product','Product','',array('id')));
    $query->where(array(
       'alias' => 'PRODUCT-NAME',
    ));
    
    $output = $modx->getValue($query->prepare());
    
    return $output;
    


  • Bingo Reply #3, 4 months, 2 weeks ago

    Reply
    Fungerar perfekt. Tack.


  • opengeek Reply #4, 4 months, 2 weeks ago

    Reply
    Du är hjärtligt välkommen!


  • Bingo Reply #5, 4 months, 2 weeks ago

    Reply
    Oops, sorry about the Swedish. Was probably too tired.

    How do I change it if I want both id and title?

    First:

    $query->select($modx->getSelectColumns('Product','Product','',array('id', 'title')));


    Then?


  • opengeek Reply #6, 4 months, 2 weeks ago

    Reply
    Easy way:
    <?php
    $product = $modx->getObject('Product', array('alias' => 'PRODUCT-NAME'));
    return $product ? implode('-', $product->get(array('id', 'pagetitle'))) : 'Nothing was retrieved!';
    


    Uses less memory (doesn't load the object):
    <?php
    $output = '';
      
    $query = $modx->newQuery('Product');
    $query->select($modx->getSelectColumns('Product','Product','',array('id', 'pagetitle')));
    $query->where(array(
       'alias' => 'PRODUCT-NAME',
    ));
    if ($query->prepare() && $query->stmt->execute()) {
        $row = $query->stmt->fetch(PDO::FETCH_ASSOC);
        $output = "{$row['id']}, {$row['pagetitle']}";
        $query->stmt->closeCursor();
    }
     
    return $output;
    


  • Bingo Reply #7, 4 months, 2 weeks ago

    Reply
    Thank you again.