PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 23, 2022

[FIXED] cakephp how to avoid the repeating columns in query result

 January 23, 2022     cakephp, cakephp-3.0     No comments   

Issue

I have a query like

$p = $this->Products->findById( $id )
              ->select(['name', 'description', 'category_id', 's.name', 'pp.price'])
              ->join([
                'table' => 'sizes',
                'alias' => 's',
                'type' => 'INNER',
                'conditions' => 's.category_id = Products.category_id',
            ])
            ->join([
                'table' => 'products_prices',
                'alias' => 'pp',
                'type' => 'LEFT',
                'conditions' => 'pp.size_id = s.id AND pp.product_id = Products.id',
            ]);

The problem is if the product has 10 different sizes, 10 rows will be produced with repeating name, description, category_id elements

Is there a way to rewrite it so the size's name and prices are delivered as array as a sub-array?


Solution

Maybe just use Containable instead of Join? You can run a find() on your Products and contain Sizes and ProductPrices. This would get you the array/sub-array you're looking for.

The only down-side is that it would still pull products even if they don't have a matching size.

It's tough to tell what you're really going for, since you're joining on category_id, which isn't really referenced. Maybe if you explain in more detail what the goal of this query is, we could provide a better answer on how to achieve.



Answered By - Dave
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing