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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Comparing Columns in DataObjects

Go to End

3 Posts   692 Views


Community Member, 48 Posts

11 July 2012 at 11:11am

I've been wrestling with this problem for a while now and can't see how to go about it. I have 2 dataobjects (Project, Enhancement). Project has many Enhancements, Enhancement has one Project.

I was using the ProjectsID column in Enhancements to get Enhancements that haven't been assigned to a project. I also only want to get enhancements that are at certain status levels (I don't want completed enhancements to show in the list)

$enhancements = new DataObjectSet();
$enhancements->merge(DataObject::get('Enhancement', "StatusLevelsID = 1 AND ProjectsID = 0")); // Approved
$enhancements->merge(DataObject::get('Enhancement', "StatusLevelsID = 4 AND ProjectsID = 0")); // In Progress

if ($enhancements) {
$map = $enhancements->toDropdownMap('ID', 'Title');
$fields->addFieldToTab("Root.ProjectEnhancements", new AsmselectField('Enhances', 'Enhancement', $map));

This was working great until I realized that if I delete a project, there will be enhancements with a ProjectsID equal to a deleted Project ID and I won't be able to add them to another project.

So instead of just getting ProjectsID = 0, I need to get ProjectsID that don't match an existing ID for my Project class. I'm not sure how to find these.



Community Member, 46 Posts

11 July 2012 at 8:45pm

Edited: 11/07/2012 8:45pm

Just to check: Enhancement actually "has one or zero" Projects?

If that is the case, you can either remove the Link from the Enhancements before a Project is deleted, or execute an SQL query that will set them to zero. Use onBeforeDelete for that:

class Project extends ... {
    //Alternative 1
    //loop over $this->Enhancements and unset the link. Should work similar to this
    foreach($this->Enhancements() as $enhancement){
      $enhancement->Project = null;
    //Alternative 2
    //Execute SQL: UPDATE Enhancements SET ProjectID = 0 WHERE ProjectID = $this->ID;
    //in both cases make sure to call the original method, there might be important stuff in it.


Community Member, 48 Posts

12 July 2012 at 2:26am

Thanks for the help jak. I was able to get it to work using alternative 2 like:

function OnBeforeDelete() {

DB::query("UPDATE Enhancement SET ProjectsID=0 WHERE ProjectsID={$this->ID}");