Yii2 ActiveRecord Save () method problem

Source: Internet
Author: User
Tags findone
RT, which had been thought before ActiveRecord->save 方法Can be used when the data does not exist insert, when present update, and later saw this document on the Civil Service Web site:

// 新建一条记录$model = new Customer;if ($model->load(Yii::$app->request->post()) && $model->save()) {    // 获取用户输入的数据,验证并保存}// 更新主键为$id的AR$model = Customer::findOne($id);if ($model === null) {    throw new NotFoundHttpException;}if ($model->load(Yii::$app->request->post()) && $model->save()) {    // 获取用户输入的数据,验证并保存}

According to this logic, if I want to update id = 100 This data information now, if the data table does not have this record, then, so, you $model === null have to judge, if empty, instantiate one $model , and then:

$model = new Customer();$model->id = 100;.....

Do you feel that it's not elegant enough or that I ActiveRecord have a problem with my understanding?

Reply content:

RT, previously thought ActiveRecord->save 方法 can be when the data does not exist, when insert there update , later on the civil service online to see this document:

// 新建一条记录$model = new Customer;if ($model->load(Yii::$app->request->post()) && $model->save()) {    // 获取用户输入的数据,验证并保存}// 更新主键为$id的AR$model = Customer::findOne($id);if ($model === null) {    throw new NotFoundHttpException;}if ($model->load(Yii::$app->request->post()) && $model->save()) {    // 获取用户输入的数据,验证并保存}

According to this logic, if I want to update id = 100 This data information now, if the data table does not have this record, then, so, you $model === null have to judge, if empty, instantiate one $model , and then:

$model = new Customer();$model->id = 100;.....

Do you feel that it's not elegant enough or that I ActiveRecord have a problem with my understanding?

Yii Chinese official website answer

saveis based on the primary key of the table, if you pass in the primary key is the update, or vice versa is to add

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.