php - 更好的 Propel 查询

标签 php mysql propel

我有 4 个表:

  1. branches(包含分支信息)
  2. offered_class_types(每个分支都有一组可用的类(class))
  3. class_sessions(每个类(class)都有自己的类(class),比如白天、晚上和晚上)
  4. class_dates(每个日期对应一个 session )

所以我的流程是:每个日期都对应一个 session (通过一个直接链接两者的代码),它通过两件事对应一个类型:1. 分支 ID 和 2. 类名(分支可以提供相同的类类型)可以有相同的 session )。每个类类型对应于使用与 session 表对应的相同分支 ID 的分支表。

我想将这段代码变成一个查询,而不是现在的两个查询。在切换到 Propel 之前,它是在一个查询中。

$class = ClassDatesQuery::create()->findPk(160);
$classSession = $class->getOfferedSessionsRelatedByCode();
$classType = OfferedClassTypesQuery::create()
   ->filterByType($classSession->getClassname())
   ->filterByBranchid($classSession->getBranchid())
   ->find();

最佳答案

只要您在两个表之间有一个简单的关系,一个简单的查询(类似于下面的查询)就会浮出水面:

$classType = OfferedClassTypesQuery::create()
  ->useClassDatesQuery()
    ->filterByPk(160)
  ->endUse()
  ->filterByXXX(YYY)
  ...
  ->find();

复杂的是你有不止一个连接条件,而这些条件在查询之前是未知的。

至少有两 (2) 种替代方法。

选项一:

编写您的原始 SQL 查询,并针对您的数据库连接运行它,然后使用适当的对象/类包装器手动混合结果集,如下所示:

$db = Propel::getConnection();
$sql = 'SELECT OfferedClassTypes.* FROM ...';
$query = $db->prepare($sql);
$formatter = new PropelObjectFormatter();

// Here you specify the class that matches
// the expected results set
$formatter->setClass('OfferedClassTypes');
$classType = $formatter->format($query);

注意 OfferedClassTypes.*,因为您只需要该表中的列,这样您就可以通过匹配的对象进行水化

选项二:

将原始 SQL 查询放入 View 中,引用:

Propel custom sql for view tables

所以你可能会这样定义你的 View :

CREATE VIEW ViewOfferedClassTypes AS
  SELECT
    ClassDates.ID as ClassDateID,
    OfferedClassTypes.*
    ...

然后在您的架构中您将拥有:

<table
  name="ViewOfferedClassTypes"
  phpName="ViewOfferedClassTypes"
  readOnly="true"
  skipSql="true">
  <!-- More columns from the OfferedClassTypes table -->
  <column name="ClassDateID" ... /><!-- From ClassDates table -->
</table>

请注意 ClassDateID 列,以便您可以在过滤器中使用:

$classType = ViewOfferedClassTypesQuery::create()
  ->filterByClassDateID(160)
  ->find();

选项 1 快速而肮脏,而选项 2 更精致但更清晰/更有条理。

希望这对您有所帮助,祝您好运。

关于php - 更好的 Propel 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27937413/

相关文章:

正则表达式 : find inline javascript in HTML document

mysql - 为什么我必须在 MySQL 查询中的表名周围使用反引号?

转换时区选择过滤器之间的Mysql

php - 在自定义字段上插入 2 双连接

php - 将相同的元数据插入多个表的相同列时,如何减少重复代码?

php - 将 2 个子表与一个父表连接起来,不重复

php - 动态菜单的交替颜色

php - 插入如何进行多对多查询 "OR"两个表

php - 不使用驼峰命名法命名 PHPUnit 测试方法会有什么后果?

php - mysqli_real_escape_string 存在漏洞