• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
get from 2 tables which are connected

i have article, cats and article_cats table.

article table fields:
- id
- name

cats table table fields:
- id
- name

article_cats table fields:
- id
- article_id
- cat_id

now i wonna select that article with this fields:
- id
- name
- cats (array of categories)

How can i do this with codeigniter query helper and with 1 query ?

Look into JOINs using mysql to get related data from other tables and you can use GROUP_CONCAT() to grab all of the categories for each article.

Once you figure out the regular SQL to do the query you can convert it to active record.

I tried with JOIN, but no success Sad
Can you give me code and i will check ?

Post what you have tried.

I removed that code, now my code is doing 3 sql queries.
First get article info, then function that get cats for that article and get cat name for each cat, and at end save that object to $data->cats.

Can you give me example for join method, so i can do it on that way ?

This is the query, but analize it, and read documentation to learn well.

  a.id AS article_id ,
  a.name AS article_name ,
  COUNT( c.id ) AS num_categories ,
  GROUP_CONCAT( c.name ) AS categorie_names
  article AS a
  article_cats AS ac
  ( a.id = ac.article_id )
  cats AS c
  ( ac.cat_id = c.id )

if you need to add conditions, use WHERE and/or HAVING depending on the field


That was a mistake vitoco... CroNiX was doing it right. the topic starter didnt try anything at all i guess, just want to get working code and cronix tried to force him to learn something by himself - you just blew it Sad

I don't get JOIN at all, tomorrow i will analyze this code, and implement it in mine.
I just gave an example what i mean, this is not my tables..
Thank you all.

I analyzed this code, and i tried with right and only join method, result is the same, so can someone explain me what is the difference ?

I have 1 more question, can this field categorie_names be an array with id and name of each categorie ?
Is this possible in mysql ?

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.