dongshicuo4844 2014-01-13 11:33
浏览 137
已采纳

PHP(Phalcon框架)和MySQL:模型关系与JOIN

For example there are 3 tables:

  • products
  • product_images
  • product_specs

And there are one-to-one relationships in models of this 3 tables.

By showing 50 products on page - it get more +2 extra queries inside cycle, so in total there are 150 rows and cool object:

$products = Products::find();
foreach ($products as $product)
{
    $product->name;
    $product->images->filename;
    $product->specs->volume;
}

Or just create custom method in Products Model and JOIN all necessary tables:

$products = Products::getComplete();
foreach ($products as $product)
{
    $product->name;
    $product->imageFile;
    $product->specVolume;
}

So, i'm wondering: is 1st practice is useful and don't make high load on MySQL daemon or slowing drastically php script execution time?

  • 写回答

1条回答 默认 最新

  • douzong6649 2014-01-13 15:51
    关注

    Answer to your first question: that practice could be useful, but would depend on your exact implementation.

    But, you are right. Using built-in one-to-one relationship will query the related model each time it's referenced which is intensive. So:

    $products->images
    

    is a new query for each record.

    Fortunately, there is a better, more efficient way that achieves the same result - PHQL.

    Since a one-to-one is basically a joined table that is called up via a second query (when it really doesn't need to), you could accomplish the same thing by doing something like:

    $products =
        (new \Phalcon\Mvc\Model)
            ->getModelsManager()
            ->executeQuery(
                "SELECT   products.*, product_images.*, product_specs.* ".
                "FROM     Products    AS products ".
                "JOIN     ProductImages AS product_images ".
                "ON       products.id = product_images.product_id ".
                "JOIN     ProductSpecs AS product_specs ".
                "ON       products.id = product_specs.product_id");
    

    which will only do a single query and give you the same information you wanted before.

    This is just one of those times where you have to identify expensive queries and choose an alternate method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改