Named scope - Get orphan AR without loosing primary key

0 0
2
Viewed: 12 016 times
Version: Unknown (update)
Category: Tutorials
    Written by: cma cma
    Updated by: Steve Friedl Steve Friedl
    Created: Jul 28, 2010
    Updated: 15 years ago

    You are viewing revision #2 of this wiki article.
    This version may not be up to date with the latest version.
    You may want to view the differences to the latest version or see the changes made in this revision.

    « previous (#1)next (#3) »

    Sometime, in a many-to-many relation, you need to retrieve AR that aren't linked. In practice, AR with null value in the join table. So you implements a criteria like this :

    public function scopeUnused( $useAnd = true )
        {
            $join = " left outer join composed_by j on t.ID = j.ID ";
            $condition = ' j.ID Is Null';
        
            $criteria = new CDbCriteria();
            $criteria->join = $join;
            $criteria->condition = $condition;
        
            self::getDbCriteria()->mergeWith( $criteria , $useAnd );
        
            return $this;  
        }
    

    You face the problem that your AR's pk are empty ?!! It come from the fact that the generated sql query returns by default all columns (select *). To overcome this, you need to explicitly specify the columns of your AR in the select property of the DBCriteria

    public function scopeUnused( $useAnd = true )
        {
            $join = " left outer join composed_by j on t.ID = j.ID ";
            $condition = ' j.ID Is Null';
            $select = ' t.ID, t.FIELD1, t.FIELDX';
        
            $criteria = new CDbCriteria();
            $criteria->join = $join;
            $criteria->select = $select;
            $criteria->condition = $condition;
        
            self::getDbCriteria()->mergeWith( $criteria , $useAnd );
        
            return $this;  
        }