加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 在Symfony和Doctrine中对数据库的查询太多

发布时间:2020-12-13 17:10:26 所属栏目:PHP教程 来源:网络整理
导读:的schema.yml: JobeetCategory: actAs: { Timestampable: ~ } columns: name: { type: string(255),notnull: true,unique: true }JobeetJob: actAs: { Timestampable: ~ } columns: category_id: { type: integer,notnull: true } name: { type: string(255
的schema.yml:

JobeetCategory:
  actAs: { Timestampable: ~ }
  columns:
    name: { type: string(255),notnull: true,unique: true }

JobeetJob:
  actAs: { Timestampable: ~ }
  columns:
    category_id:  { type: integer,notnull: true }
    name:         { type: string(255) }
  relations:
    JobeetCategory: { onDelete: CASCADE,local: category_id,foreign: id,foreignAlias: JobeetJobs }

action.class:

public function executeIndex(sfWebRequest $request)
  {
    $this->jobeet_job_list = Doctrine::getTable('JobeetJob')
      ->createQuery('a')
      ->execute();
  }

和模板:

<table>
    <?php foreach ($jobeet_job_list as $jobeet_job): ?>
    <tr>
      <td><?php echo $jobeet_job->getcategory_id() ?></td>
      <td><?php echo $jobeet_job->getName() ?></td>
    </tr>
    <?php endforeach; ?>
</table>

这些模板仅向数据库生成了2个查询.还行吧.但如果我这样做:

<table>
    <?php foreach ($jobeet_job_list as $jobeet_job): ?>
    <tr>
      <td><?php echo $jobeet_job->getJobeetCategory()->getName() ?></td>
      <td><?php echo $jobeet_job->getName() ?></td>
    </tr>
    <?php endforeach; ?>
</table>

我在数据库100 JobeetJob然后这生成102查询到数据库!这太多了!有可能减少这个吗?

解决方法

您目前正在“懒惰加载”JobeetCategory对象.如果你知道你将不得不多次这样做,这是低效的.您应该在初始查询上进行连接:

$this->jobeet_job_list = Doctrine::getTable('JobeetJob')
  ->createQuery('a')
  ->leftJoin('a.JobeetCategory c')
  ->execute();

这意味着将从数据库中检索所有相关的JobeetCategory对象并立即进行水合,因此您不必在以后延迟加载它们.这应该让你回到2个查询.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读