Activerecord-association: create new object (find class)

后端 未结 3 1230
我在风中等你
我在风中等你 2021-02-06 18:47

I have an model with a relation, and I want to instantiate a new object of the relations type.

Example: A person has a company, and I have a person-obje

3条回答
  •  忘掉有多难
    2021-02-06 19:20

    In PHPActiveRecord, you have access to the relations array. The relation should have a name an you NEED TO KNOW THE NAME OF THE RELATIONSHIP/ASSOCIATION YOU WANT. It doesn't need to be the classname, but the classname of the Model you're relating to should be explicitly indicated in the relation. Just a basic example without error checking or gritty relationship db details like linking table or foreign key column name:

    class Person extends ActiveRecord\Model {
        static $belongs_to = array(
                           array('company',
                                     'class_name' => 'SomeCompanyClass')
                                     );
        //general function get a classname from a relationship
        public static function getClassNameFromRelationship($relationshipName)       
           foreach(self::$belongs_to as $relationship){
              //the first element in all relationships is it's name
              if($relationship[0] == $relationshipName){
                 $className = null;
                    if(isset($relationship['class_name'])){
                      $className = $relationship['class_name'];
                    }else{
                      // if no classname specified explicitly,
                      // assume the clasename is the relationship name
                      // with first letter capitalized
                      $className = ucfirst($relationship);
                    }
                    return $className               
                }
            }   
            return null;
         }
    }
    

    To with this function, if you have a person object and want an object defined by the 'company' relationship use:

    $className = $person::getClassNameFromRelationship('company');
    $company = new $className();
    

提交回复
热议问题