MySQL让所有父母都有孩子

时间:2015-02-18 14:27:08

标签: php mysql

我有两张一对多的关系表。我需要查询,这将使我的父母与所有孩子一起回来。我可以在PHP中使用foreach parent给我所有的孩子。像这样:

查询所有家长:

SELECT * FROM parents WHERE deleted=0;

比在foreach的PHP中

SELECT * FROM children WHERE deleted=0 AND parent_id = {$parentID};

有没有办法通过一个数据库查询来完成此任务。如果有人可以给我一些教程或一些简单的例子:)

1 个答案:

答案 0 :(得分:0)

你可以这样做:

<?php
  /**
    a sample model
  **/
  class Model {
  
    public function getParentsWithChildren() {

      $out = array();
  
      //you have your PDO instance...
      $query = $pdostmt->query('SELECT * FROM parents WHERE (deleted = 0)');
  
      while ($data = $query->fetch(PDO::FETCH_OBJ)) {
        
        $out[] = array(
          $data->id, $data->column_name, $this->getChildren($data->id)
        );
        
      }
    
      $query->closeCursor();
    
      return $out;

    }

    public function getChildren($parent) {
        
      $out = array();

      $query = $pdostmt->prepare('SELECT * FROM children WHERE (deleted = 0) AND (parent_id = ?)');
      $query->execute(array($parent));

      while ($data = $query->fetch(PDO::FETCH_OBJ)) {
        
        $out[] = array(
          $data->id, $data->column_name, $data->other_column
        );
        
      }
    
      $query->closeCursor();
    
      return $out;
        
    }
    
  }
?>

你可以使用它:

<?php
  //your php file

  include('path/to/the/Model.php');

  $model = new Model;

  $parentComplete = $model->getParentsWithChildren();

?>

你可以得到一个具有这种结构的数组:

(
  0 => (
         0 => 1,
         1 => example_parent,
         2 => (
                0 => (
                       0 => 1,
                       1 => example_child_1
                     ),
                1 => (
                       0 => 1,
                       1 => example_child_2
                     )
              )
       ),
   1 => (
    //...
   )
)