Question

I have 2 tables, one holding pages, the other holding translated values for some of the pages properties:

pages -id,in_menu,created_at ... etc

page_translations - id,page_id,locale, title,content... etc (row for each locale)

I need to create a table with 2 locales - re joining the translation

pages

--- id --- title_en ---- title_he --- in_menu
    1     someTitle     Translated    true

I am using laravel (4.1) so what i did is:

Page:join('page_translations', 'pages.id', '=', 'page_translations.page_id')
->select(array('pages.id', 'page_translations.page_id as 
  pageId','page_translations.title as title_en', 'page_translations.title as 
  title_he','pages.in_menu', 'pages.created_at'))
->where('page_translations.locale','=','en')
->groupBy('page_translations.page_id');

the result sql (for ones that don't dig laravel)

select `pages`.`id`, `page_translations`.`page_id` as `pageId`,
`page_translations`.`title` as `title_en`, `page_translations`.`title` as `title_he`,

pages.in_menu, pages.created_at from pages inner join page_translations on pages.id = page_translations.page_id where page_translations.locale = 'en' group by page_translations.page_id

now I have the title twice (as title_en and title_he) and so I used another query to replace the title_he with the right value

PageTranslation::wherePageId($pageId)->whereLocale('he')->pluck('title') 

I want to know if anyone can make it in a single query call!

Was it helpful?

Solution

Just join the page_translations table twice:

Page:join('page_translations AS page_translations_en', function($join) {
    $join->on('pages.id', '=', 'page_translations_en.page_id'),
    $join->on('page_translations_en.locale', '=', 'en')
})->join('page_translations AS page_translations_he', function($join) {
    $join->on('pages.id', '=', 'page_translations_he.page_id'),
    $join->on('page_translations_he.locale', '=', 'he')
})
->select(array('pages.id AS page_id', 'page_translations_en.title as title_en', 'page_translations_he.title as 
  title_he','pages.in_menu', 'pages.created_at'))
->groupBy('page_translations.page_id');

Can't guarantee that will work out-of-the-box as I don't have a copy of your schema, but you get the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top