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.

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

报告相同问题?

悬赏问题

  • ¥15 软件供应链安全是跟可靠性有关还是跟安全性有关?
  • ¥15 电脑蓝屏logfilessrtsrttrail问题
  • ¥20 关于wordpress建站遇到的问题!(语言-php)(相关搜索:云服务器)
  • ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
  • ¥15 Java+vue部署版本反编译
  • ¥100 对反编译和ai熟悉的开发者。
  • ¥15 带序列特征的多输出预测模型
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?