views:

27

answers:

2

Hello. I have two tables:

1. plan_payment_type:
   id
   plan_id

2. plan
   id
   payment_period

It is Foreign key between plan_payment_type.plan_id and plan.id. In my code I know a $plan_payment_type_id.

My task is to select payment_period. Steps:

  • Select plan_id from plan_payment_type
  • Select payment_period from plan with selected plan_id

How can I do it with one query in Zend Framework? Thank you very much.

+2  A: 

The following SQL statement and PHP code correspond to each other:

SELECT
  t.id AS plan_payment_type_id,
  p.id AS plan_id,
  p.payment_period
FROM
  plan_payment_type AS t
  INNER JOIN plan AS p ON p.id = t.plan_id
WHERE
  p.id = { SQL query param for $plan_payment_type_id }


$select = $db->select()
          ->from(array('t' => 'plan_payment_type'),
                 array('id' => 'plan_payment_type_id'))
          ->join(array('p' => 'plan'), 'p.id = t.plan_id',
                 array('id' => 'plan_id', 'payment_period'))
          ->where('p.id = ?', $plan_payment_type_id);
Tomalak
Thanks. It work fine with little changes.
Alexander.Plutov
+1  A: 

Before everything I would organize them differently. Is not the plan_types that should have a plan.id. This is not logical. You hava a table with plan_types which has an plan.id and a plan.name and the relation is in the plan table through the plan.type_id.

This dependencies are solved this way:

class Payment_Plan extends Zend_Db_Table_Abstract
{
    protected $_name            = 'plan';
    protected $_referenceMap    = array(
        'Plan' => array(
            'columns'           => 'plan_id',
            'refTableClass'     => 'Plan',
            'refColumns'        => 'id'
        )

}

class Plan_Type extends Zend_Db_Table_Abstract
{
    protected $_name            = 'plan_types';
    protected $_dependentTables = array('Plan_Type');
}

Later you can have in the PlanRow Class a function :

public function type() {
    return $this->findParentRow('Plan_Type');
}

and for getting all the plans of type x in the Plan_type row class

public function entries() {
    return $row->findDependentRowset('Plan');
}
Elzo Valugi
`Tomalak` answer is better for me. Thanks, `Elzo Valugi`.
Alexander.Plutov
+1 because you are right with regard to DB layout. Having a `plan_id` on `plan_payment_type` makes no sense to me either.
Tomalak