0

i.e : i have 2 tables

  1. Product ( id, name )
  2. Photo ( id, name, photo_id )

And I need to get result in array like this:

array(
 'id' => 1,
 'name' => product,
 'photos' => array(
      array('id' => 1, 'name' => 'photo1')
      array('id' => 2, 'name' => 'photo2')
  )
}

Is it possible in PHP using clear SQL?

I know that is possible to get 2 arrays and connect it but I have many records and I dont want to wase time to quering.

3
  • Try using nested queries maybe? You need to provide more information. Your table structure with some sample data along with the query that you've tried so far. Commented Apr 14, 2015 at 13:28
  • what did you try so far? show us your current code please Commented Apr 14, 2015 at 13:33
  • Why you are having id as well photo_id in your photo table 2 Photo ( id, name, photo_id ) just use product_id_fk instead of photo_id and your are done. Commented Apr 14, 2015 at 18:07

3 Answers 3

1

You have to add a foreign_key in your photo table "product_id".

Then create a method getPhotos() in your Product class with will collect all photos for your product.

Sign up to request clarification or add additional context in comments.

Comments

0

Is it possible in PHP using clear SQL?

Not in a single SQL call. With a single call, this is the closest you can get:

array(
 'id' => 1,
 'name' => product,
 'photo_id' => 1,
 'photo_name' => 'photo1')
),
array(
 'id' => 1,
 'name' => product,
 'photo_id' => 2,
 'photo_name' => 'photo2')
)

Your only choice for the format you want is to run queries separately or to combine them into the data structure you want.

1 Comment

Hi, all thank you for many answers. In my first post I have make mistake. In Photo table I Have product_id NOT photo_id ... pfff. So if I will use that query "SELECT * FORM product p LEFT JOIN photo ph ON p.id = ph.product_id GROUP BY p.id" I return only one photo for product. So how I have to do it?
0

As mentioned, this is not possible with SQL. SQL is based on the relational model which is a 1-Normal-Form data model. That means, the result relation is also flat (no nested relations in a relation).

However, there are good frameworks which generate intermediary models in your corresponding target language (e.g. Python, Java, ...) that circumvent the impression of a flat data model. Check for example Django.

https://docs.djangoproject.com/en/1.8/topics/db/models/

Moo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.