K
K
kllpff2020-08-09 15:41:37
Yii
kllpff, 2020-08-09 15:41:37

Am I saving models correctly?

Hello! I'm in the process of learning Yii2, I'm currently working on a product save implementation.
After submitting the form in the model for this form, validation takes place and then I immediately need to save the data to different models, for example:

$product = new Product();
$product->name = $this->name;
...
$category = new ProductCategory();
$category->category_id = $this->category_id;
$category->product_id = $product->id;
...
$brand = new ProductToBrand();
$brand->brand_id = $this->brand_id;
$brand->product_id = $product->id;
...
$url = new UrlBase();
$url->alias = $this->alias;


And so I thought, how is this the right approach? After all, there are best practices, probably. Tell a newbie please. It would be great to see links to good and elegant implementation examples.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-08-09
@kllpff

1. It is not clear what is $this->category_idwhere it comes from? If there is just an ID, then this ID can be changed. It is more correct to first request a category and, if the category is found, receive its ID $category->id
2. See the documentation on how to save using AR links. There is a method for thislink()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question