From 62438611382b45904671bcc8eca465e7dcf99f33 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Thu, 10 Jan 2013 12:41:16 -0500 Subject: [PATCH] AR WIP --- framework/db/ActiveRecord.php | 27 ++++++++++++++++++++++++++- framework/db/ActiveRelation.php | 2 +- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/framework/db/ActiveRecord.php b/framework/db/ActiveRecord.php index 0a3bbe3..39209bb 100644 --- a/framework/db/ActiveRecord.php +++ b/framework/db/ActiveRecord.php @@ -856,5 +856,30 @@ abstract class ActiveRecord extends Model return $this->__isset($offset); } - + /** + * @param string $name + * @param ActiveRecord $model + * @throws Exception + */ + public function linkWith($name, $model) + { + $getter = 'get' . $name; + if (!method_exists($this, $getter)) { + throw new Exception('Unknown relation: ' . $name); + } + $relation = $this->$getter(); + if (!$relation instanceof ActiveRelation) { + throw new Exception('Unknown relation: ' . $name); + } + if ($relation->multiple) { + foreach ($relation->link as $a => $b) { + $key = $this->$b; + if ($key === null) { + throw new Exception('key null'); + } + $model->$a = $this->$b; + } + return $model->save(false); + } + } } diff --git a/framework/db/ActiveRelation.php b/framework/db/ActiveRelation.php index f6d5683..1ef749f 100644 --- a/framework/db/ActiveRelation.php +++ b/framework/db/ActiveRelation.php @@ -41,7 +41,7 @@ class ActiveRelation extends ActiveQuery * must be the corresponding columns from the primary table. * Do not prefix or quote the column names as they will be done automatically by Yii. */ - protected $link; + public $link; /** * @var array|ActiveRelation */