Sort field in relations table (one to many), how to insert the sort number?
-
23-09-2019 - |
Question
I have two tables, content and images (and a ContentImages table for the one to many relation, so that's actually 3 tables).
The following code saves the relation (in the action > updateContentFromRequest() ):
$ids = $this->getRequestParameter('contentImages');
if( isset($ids) ){
$ImagesTable = Doctrine::getTable('Content')->getRelation('Images')->getTable();
$associationName = Doctrine::getTable('Content')->getRelation('Images')->getAssociationTable()->getOption('name');
$this->content->$associationName->delete();
foreach ($ids as $id){
$id = explode('/', $id);
$this->content->get('Images')->add($ImagesTable->find($id));
}}
I changed the model to include a sort field in the ContentImages table:
content_id
image_id
sort (numeric)
The sort number is simply that, a number (0,1,2,3 etc)
$sort = $this->getRequestParameter('contentImagesSort');
How do I save the sort number? I do not want to add a sort field to the Image table because that could create difficulties when images are re-used across more content items. When a content item is new I do not know the ID yet so I'm a bit stumped...
Solution
You should add One to Many associations on your join Table, like:
ContentImages:
relations:
Image:
local: image_id
foreign: id
Content:
local: content_id
foreign: id
As such, you will be able to query directly the join table like this :
$q = Doctrine_Query::create()
->from('Content c')
->leftJoin('c.ContentImages ci')
->leftJoin('c.Images i')
->execute();
Then you can access to ContentImages using
$content->ContentImages->setSort('your sort');
This should do the trick :)
OTHER TIPS
If you have generated models you can add to your setUp method the orderBy parameter:
$this->hasMany('PICTURE as PICTURES', array(
'local' => 'BRAND_ID',
'foreign' => 'PICTURE_ID',
'refClass' => 'BRAND_PICTURE',
'orderBy' => 'your_field DESC'
));
orderBy should do the trick
I do things a little a differently from what you've got above so not completely sure this is what you're asking, but can't you just save the object with whatever is needed for it?
$association = // load up existing entry from ContentImages using whatever method
$association->setSort($the_sort_I_want_to_add);
$association->save();
Or querying it...
$association = // load up existing entry from ContentImages using whatever method
$my_unknown_sort = $association->getSort();
Hope that helps.