S
S
Sergey2016-02-03 15:56:22
Yii
Sergey, 2016-02-03 15:56:22

Why doesn't save() work in Yii2?

There is a code like this:

$model=new Products();
$model=$model->findOne(['id'=>1]);
$model->name="Новое название";
$model->save();

That is, you need to overwrite the field, but save does not work and is highlighted in the IDE as "not found in class null|static"
If you remove the line $model=$model->findOne(['id'=>1]);
then it creates a new product, but how can I edit this one? I don't see any error here though.
class Products extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'products';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'url', 'price','quantity','category_id','options_id','mark','model'], 'required'],
            [['price'], 'number'],
            [['full_desc'], 'string'],
            [['category_id','options_id','quantity','status'], 'integer'],
            [['name', 'url'], 'string', 'max' => 50],
            [['short_desc'], 'string', 'max' => 250]
        ];
    }
}

PS I know that in addition to name there are more fields and they are marked as required, I also specify them when editing, I just didn’t write them in the example so as not to complicate readability

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Andrey Sedyshev, 2016-02-03
@ musikant777

$model = Product::findOne(['id'=>1]);
$model->name="Новое название";
$model->save();

Read about active record in Yii2: www.yiiframework.com/doc-2.0/guide-db-active-recor...

M
Maxim Timofeev, 2016-02-03
@webinar

Very confusing $model=$model->findOne(['id'=>1]). Probably worth doing this:

$oldmodel=Product::findOne(['id'=>1]);
$model=new Product();
$model->attributes = $oldmodel->attributes;
$model->name="Новое название";
$model->save();

If I understand your goals correctly

N
Nikita096, 2017-01-03
@Nikita096

For some reason, two rules for one field conflict

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question