I am fighting with Yii to understand the way it works. In the book I can’t find an example about how to save, delete and create related objects of a database object.
Example: I have a User and an Address. Assuming relations are set up, I want to create a user, create an address and save the relation at the same time.
How can I do this?
I thought there would be something like
$user = new User;
$user->name = 'Mike';
$address = new Address;
$address->street = 'Main road 27';
$user->save( $address );
Sure the coding does not match Yiis way of handling, but I wonder how I can do this? Same for Deleting, e.g. I want to delete a user and delete his address at the same time. Ok, this I guess I would do by ForeignKey definition.
Anyway, is there a more detailed how to somewhere about basic AR operations in combination with relationships and such?
tbl_address
id primary
user_id foreign key
street varchar
.
.
User Model
public function relations()
{
return array(
'address'=>array(self::HAS_ONE, 'Address', 'user_id '),
);
}
Address Model
public function relations()
{
return array(
'user'=>array(self::BELONGS_TO, 'User', 'user_id '),
);
}
In most cases, each model will have it’s own html form. But in your case, you’ll probably want a form to manage the user and his/her address. In your controller you’ll have to perform 2 saves - 1 for the User and 1 for the Address.
$user = new User();
$user->first_name = 'Mike'; // Or get the data from the submitted form.
if ($user->save())
{
$address = new Address();
$address->street = '125 King St.'; // Or get the data from the submitted form.
$address->user_id = $user->id; // Link by ids.
$address->save();
}
Hello, just few days working with yii. Have a simple problem: can’t save the object using the way above. I have a Gallery, and during its creation I want to attach a cover which is new Picture. actionCreate():