Jump to:

3373 Posts in 999 Topics by 712 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Importing CSV data to an Object with a many_many relation

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 2128 Views
  • baba-papa
    Avatar
    Community Member
    279 Posts

    Importing CSV data to an Object with a many_many relation Link to this post

    I´m trying to import CSV data. One column of the CSV should be imported as a many_many relation. The CSVBulkLoader can manage relationCallbacks on a has_one relation but what about many_many? Can anyone provide a code example or good hint?

  • Double-A-Ron
    Avatar
    Community Member
    599 Posts
  • baba-papa
    Avatar
    Community Member
    279 Posts

    Re: Importing CSV data to an Object with a many_many relation Link to this post

    I solved my issue but this isn´t the elegant way. I import my csv data with fgetcsv(). The value of the field that represents the many_many relation is converted to an array with explode(). The elements of this array get saved to the table that represents the many_many relation. I did this with

    $sql = "INSERT INTO `database`.`Relation_table` (`column1`, `column2`) VALUES ('$studioID', '$contract->ID');";
    DB::query($sql);


    This is no more ORM, that´s why I call my way less elegant, but it works.

    DataObject::getManyManyFilter might be the method to do this the right way but nor did I understand it yet neither is it documented.

  • Ingo
    Avatar
    Forum Moderator
    801 Posts

    Re: Importing CSV data to an Object with a many_many relation Link to this post

    I'm just working on a subclass of CSVBulkLoader, called MemberCsvBulkLoader. See first cut: http://pastie.org/723161
    It can take multiple group codes inside a new "Groups" column in the CSV data for each member row, and resolves them automatically into manymany relationships.

    The main issue here is that for each relationship, you'd probably want some unique criteria other than a primary key to make the CSV file independent of your specific database keys. In the case of $member->Groups() relations, thats already solved for us with the "Code" property.

    This class will most likely find its way into SilverStripe trunk soon, together with a new "Import" tab in the admin/security section

    2128 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.