Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions

CSVBulkUploader with belongs_many_many


Reply

214 Views

Avatar
msawebdev

1 May 2014 at 4:34pm Community Member, 15 Posts

Hi all hope somebody can point me in the right direction here.

I have a Dataobject (Product) which has many_many relationship on SpareParts dataobject that was a belongs_many_many relationship to Product. A product has many spareparts and a sparepart can belong to many products.

I am trying to create a CSVBulkUploader to add SpareParts from a csv file and have created the following:

<?php
class Product extends DataObject
{
   public static $api_access = true;
   
   public static $db = array(      
'Title' => 'Varchar(255)',
'SAP_MaterialNumber' => 'Varchar(255)',
'Model' => 'Varchar(255)',
'ModelAlias' => 'Varchar(255)',
'EAN_Code' => 'Varchar(255)',
'Fineline' => 'Varchar(255)',
'Description' => 'HTMLText',
'MRP_Type' => 'Varchar(4)',
   );
   
   public static $has_one = array(
'ProductImage' => 'Image',
'Brand' => 'Brand',
'SubBrand' => 'SubBrand',
'ProductCategory' => 'ProductCategory',
'ProductSubCategory' => 'ProductSubCategory',
   );

public static $has_many = array(
'Documents' => 'ProductDocument',
'Notes' => 'ProductNote'
);

public static $many_many = array(
'SpareParts' => 'SparePart'
);
}

<?php

class SparePart extends DataObject
{
   
   public static $db = array(      
'Title' => 'Varchar(100)',
'PartNumber' => 'Varchar(100)',
'Availability' => 'ENUM("In-Stock, Available, Not-Available")',
'ListPrice' => 'Currency',
//'Active' => 'Boolean'
   );

   public static $many_many = array(
'PartsListItems' => 'PartsListItem'
   );

public static $belongs_many_many = array(
'Products' => 'Product'
);
}

<?php
class SparePartsBulkLoader extends CsvBulkLoader {

public $columnMap = array(
'Product' => 'Products.SAP_MaterialNumber',
'PartNumber' => 'PartNumber',
'Title' => 'Title',
'Availability' => 'Availability',
'ListPrice' => 'ListPrice',
);

public $relationCallbacks = array(
'Products.SAP_MaterialNumber' => array('relationname' => 'Products', 'callback' => 'getProductByMaterialNumber' )
);

public static function getProductByMaterialNumber(&$obj, $val, $record) {
return Product::get()->filter('SAP_MaterialNumber', $val)->First();
}

}

CSV:
Product,PartNumber,Title,Availability,ListPrice
M12CHZ-0,634918001,SHOE STAMPING,Available,1.1
M12CHZ-0,661113008,TAPTITE SCREW STEEL TORX (6PCS),In-Stock,0.9
M12CHZ-0,563259001,WATERPROOF BARRIER RUBBER NBR60,Not-Available,0.85

When I run this the relationship to products does not happen (no products set on sparepart).

The question is can this be done through the framework or should the relationship be done with raw sql?

all help greatly appreciated.