ActiveRecord join on other column than 'id'

Discuss about Group-Office development here

Moderator: Developers

huisvanheden
Posts: 5
Joined: Mon Sep 09, 2013 11:15 pm
Location: Belgium
Contact:

ActiveRecord join on other column than 'id'

Postby huisvanheden » Fri Apr 18, 2014 10:57 am

I have two models that need to be joined but there I don't seem to find how I can join them if the key of the second table is not labeled as 'id'.
I created the models and controllers for both and want to show it in a grid using a json store using the GO.url router.

The error that is shown when doing the join

Code: Select all

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
Example scenario:

Code: Select all

table 1

  id  |   name   |  table2_id
-------------------------------
   1  |   first  |     21
   1  |  second  |     22

table 2

  key  |  name
----------------
   21  |  foo
   22  |  bar

result

   name | table2_id
---------------------
  first | foo
 second | bar
I defined in the table1 model a relation that table_id2 belongs to table2.
In the tabel1 controller I use the formatColumns function to access the model using the $model object to change the table2_id column to the name.
Do I have to override or define some function in the controller to change the default behaviour or do I have to write an own actionStore function for that?
Huis van Heden
Group Office Reseller
huisvanheden
Posts: 5
Joined: Mon Sep 09, 2013 11:15 pm
Location: Belgium
Contact:

Re: ActiveRecord join on other column than 'id'

Postby huisvanheden » Mon Apr 21, 2014 9:59 pm

If somebody is looking for the solution I used is to override the primaryKey() function of the GO_Base_Db_ActiveRecord class for the model class.
Don't know if this is the best solution but it works.
Huis van Heden
Group Office Reseller
richarddodd
Posts: 66
Joined: Fri Jun 21, 2013 2:55 pm

Re: ActiveRecord join on other column than 'id'

Postby richarddodd » Fri May 02, 2014 8:32 am

If you use the relation framework to manage the join for you, then it expects the joining id to be whatever you set primaryKey() to (defaults to id but can be set to anything).

There is also the option to manually specify the join - look at the source for GO_Base_Db_FindParams, especially the documentation for join(). If you do a manual join, you'll need to add fields you want to return to the 'select' field.

I'm not sure I fully understand manual joins - I've used them in the 'WHERE' clause successfully, but not really used them when I actually wanted to SELECT fields in them.
huisvanheden
Posts: 5
Joined: Mon Sep 09, 2013 11:15 pm
Location: Belgium
Contact:

Re: ActiveRecord join on other column than 'id'

Postby huisvanheden » Mon May 05, 2014 1:04 pm

Ok, thanks for the extra information ;)
Huis van Heden
Group Office Reseller

Who is online

Users browsing this forum: No registered users and 1 guest

cron