【问题标题】:Sort field in relations table (one to many), how to insert the sort number?关系表中的排序字段(一对多),如何插入排序号?
【发布时间】:2011-02-02 20:10:25
【问题描述】:

我有两个表,内容和图像(还有一个用于一对多关系的 ContentImages 表,所以实际上是 3 个表)。

以下代码保存关系(在操作> 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));
    }}

我更改了模型以在 ContentImages 表中包含一个排序字段:

content_id
image_id
sort (numeric)

排序号就是一个数字(0、1、2、3等)

$sort = $this->getRequestParameter('contentImagesSort');

如何保存排序号?我不想在图像表中添加排序字段,因为当图像在更多内容项中重复使用时,这可能会造成困难。当内容项是新的时,我还不知道 ID,所以我有点难过......

【问题讨论】:

    标签: doctrine database-relations


    【解决方案1】:

    如果你已经生成了模型,你可以在你的 setUp 方法中添加 orderBy 参数:

    $this->hasMany('PICTURE as PICTURES', array(
        'local' => 'BRAND_ID',
        'foreign' => 'PICTURE_ID',
        'refClass' => 'BRAND_PICTURE',
        'orderBy' => 'your_field DESC'
    ));
    

    orderBy 应该可以解决问题

    【讨论】:

      【解决方案2】:

      您应该在联接表上添加一对多关联,例如:

      ContentImages:
        relations:
          Image:
            local: image_id
            foreign: id
          Content:
             local: content_id
             foreign: id
      

      因此,您将能够像这样直接查询连接表:

      $q = Doctrine_Query::create()
        ->from('Content c')
        ->leftJoin('c.ContentImages ci')
        ->leftJoin('c.Images i')
        ->execute();
      

      然后您可以使用访问 ContentImages

      $content->ContentImages->setSort('your sort');
      

      这应该可以解决问题:)

      【讨论】:

        【解决方案3】:

        我做的事情与你上面所说的有点不同,所以不完全确定这是你要问的,但你不能用它需要的任何东西来保存对象吗?

        $association = // load up existing entry from ContentImages using whatever method
        $association->setSort($the_sort_I_want_to_add);
        $association->save();
        

        或者查询它...

        $association = // load up existing entry from ContentImages using whatever method
        $my_unknown_sort = $association->getSort();
        

        希望对您有所帮助。

        【讨论】:

        • 我认为你正在做一些事情,非常聪明! :) 我目前通过覆盖(自动生成的)saveContent 函数做了一个解决方法,我可以在那里请求内容的 id 并对附加的图像进行更新。
        • 嘿,马克,好 Q.. 曾经难倒我.. 我也覆盖了 saveRelation 方法并设置了排序
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        相关资源
        最近更新 更多