activerecord - Using Active Record, how can I save child's detail information through its parent? -
i'm using parent->child (master->detail) relation in yii2 active record
when want create child, have manually fill parent info this:
relation: client (1) ---> (n) comments
class clientcontroller extends \yii\web\controller { public function actionaddcomment() { $comment = new comment; if ($comment->load(yii::$app->request->post())) { $comment->client = $this->id; // client id $comment->save(); } return $this->render('view', ['comment'=>$comment]); } } i've optimized it, creating comment method that:
class comment extends activerecord { public function newcomment($client) { $comment = new comment; $comment->client = $client; // client id return $comment; } } and have gone through beforesave in comment model, still not sure if there better way.
is there like:
$comment = new comment(yii::$app->request->post()); $client->save($comment); // here parent writing information child or one-liner shortcut:
$client->save(new comment(yii::$app->request->post()); without having create logic in beforesave?
yes, recommend use built in link() , unlink() methods provided active record can use in controller relate or unrelate 2 models either share many-to-many or one-to-many relationship.
it has optional $extracolumns attribute additional column values saved junction table if using link( $name, $model, $extracolumns = [] )
so code may :
$comment = new comment; if ($comment->load(yii::$app->request->post())) { $comment->link('client', $this); } check docs more info.
now use code relate models, depend on how app structured. i'm not sure if doing through triggered event practice, need remember errors may happens , may need evaluate scenarios or logic before throwing exceptions. in case, prefer use code controllers.
sometimes need build specific action did actionaddcomment(), in other cases when post request meant update parent model , update related child models @ once, parent's update action clientcontroller::actionupdate() may place so, maybe job :
$params = yii::$app->request->post(); $client->load($this->params, ''); if ($client->save() === false && !$client->haserrors()) { throw new servererrorhttpexception('failed update object unknown reason.'); } foreach ($params["comments"] $comment) { // may sure both models exists before linking them. // in case i'm retrieving child model db don't // have validate while need id post request $comment = comment::findone($comment['id']); if (!$comment) throw new servererrorhttpexception('failed update due unknown related objects.'); // according documentation, link() method throw exception if unable link 2 models. $comment->link('client', $client); ...
Comments
Post a Comment