Deep Exploration of Create Method in Thinkphp

  • 2021-06-29 10:38:01
  • OfStack

Due to problems encountered with create () method in thinkPHP, create () was tracked to explore the create () method in one step.
The original create () method had two parameters. The first parameter was the well-known data parameter and the second was the hidden $type parameter. So what is this parameter used to control?
//Status $type = $type ?$type!empty ($data[$this- > getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT);
After careful consideration of this sentence, we found that this hidden parameter is used to indicate what the database is actually doing. 1 is the insert operation and 0 is the update operation.
By default, this parameter does not need to be assigned because it is automatically recognized by the system

It recognizes this:

If you pass in data with the same field as the primary key, the database operation defaults to the update operation. This judgment is mainly because in most cases the primary key is default self-increasing. Insert operation 1 generally does not assign a value to the primary key, but the problem is here


Recent projects directly use the number as the primary key. The number can not be self-increasing but has a fixed format and must be entered.
But the system automatically treated my typing as an update operation, and my auto-complete code was written as follows:

protected $_auto = array(
        array('majorid','maxmajoridadd1',1,'callback'),
    );


The third parameter, 1, looks at the manual to see that this autocomplete operation was performed at the time of insertion.
The system treats my insertion as an update, and the auto-completion code I set will automatically fail and not be executed.

You can write this when it happens that you also want to enter the primary key field value

create($_POST,1)

Tell the create method directly that this operation is an insert operation

This is a very difficult problem to find. Recently, many people have encountered this problem, so I want to write an explanation.

It's also possible that your Model class name was written incorrectly and so on. I've made this mistake. It's common to have more than one letter and fewer than one letter.

Basically automatic validation/completion failures are the two cases

More readers interested in thinkPHP-related content can view this site's topics: Introduction to ThinkPHP, Summary of thinkPHP Template Operating Skills, Summary of ThinkPHP Common Methods, Introduction to smarty Templates, and Technical Summary of PHP Templates.

I hope that the description in this paper will be helpful to everyone's PHP program design based on the ThinkPHP framework.


Related articles: