Save and related record

Hi,

I was wondering if Yii saves related records. I’ve tried and it doesn’t seem to work like Rails or Symfony.

Am I wrong?

If I am, could you provide an example?

Thanks a lot

your means:

$post = Post::model()->findByPk(10);

$post->author->name = ‘Jerry’;

$post->save();

$post->author->name is changed to ‘Jerry’ ?

not supported seemingly~

No I meant something like

$post = new Post;

$post->author = new Author;

Then if I do $post->save(); the author gets also save and the foreign key is automatically assigned

This question let’s qiang to answer, I want to know too~

Short answer: Not supported.

IMO this would create more overhead than it’s worth. The problem is not so much with creation but merely with updating related records. Simple example:

  1. Author HAS_MANY Posts.

  2. You load an author with all related post objects in an array ($author->posts).

  3. You want to delete a single post for that author, so you remove it from the array $author->posts.

  4. When you $author->save(), the removed post should now get deleted from db.

So the above means, whenever you call save(), AR would also have to re-check if one of the related objects has been removed. This can get complicated and time consuming very quickly.

As Yii tries to keep everything as slim and simple as possible i think it’s perfectly o.k. to manually create related objects. That gives full control, there’s only minimal extra code required and everything is pretty easy to understand.

Thanks, Mike.

Just wanted to know.

Do you know if I can use a transaction to save a bunch of objects from different models in a safe manner?

Can’t say for sure as i never used them. But i think yes, they do, as the transaction is created from the (shared) CDbConnection, not the model:


$transaction=$model->dbConnection->beginTransaction();



I has been looking for the same functionality as well (for example LINQ in C# works in this way).

It seems that this extension may do the job:

http://www.yiiframework.com/extension/eadvancedarbehavior/