1. Defining the correlation model
In Laravel, we can complete the correlation query by defining the following model.
Class MyPost extends eloquent {public function Mypostinfo () { return $this->hasone (' Mypostinfo ');} } Class Mypostinfo extends eloquent {}
2. Using the correlation model
myPostInfo()
the Camel naming convention is used here, but we can use the snake rule when reading a postinfo. The following code is possible:
$post = Mypost::find (1); $post _info = $post->mypostinfo; Example 1$post_info = $post->my_post_info; Example 2
The Laravel allows both methods, but there is no reasonable handling of conflicts caused by the use of two types of naming.
3. Cache invalidation
If we use the above two examples at the same time, one of the caches will be invalidated. In the model's relations variable, the associated model that has been read is cached, but when we read it with a different rule name, it invalidates the previous cache. For example
$post _info = $post->mypostinfo; $post->relations = [' mypostinfo ' = ' = ' ...]; $post _info = $post->my_post_info;//$post->relations = [' mypostinfo ' + = ..., ' my_post_info ' = ...];
So if you don't want the cache to fail, you have to use only one naming method in your project to read the relational model. Laravel recommended camel case.
4. ToArray () method invalidation
If both are used at the same time, another problem is to cause Model::toArray()
failure. Because the toArray()
method first went to relations
find the association model of the snake case name, and then went to see Camel.
So if you use a toArray()
method to convert the model, avoid using both.
5. Easy to make mistakes in the location
The most error-prone code is this:
Mypost::with (' Mypostinfo ')->get ();
When using the with Go Eagerload Association model, you must use and define the method with the same name as the key to read, so the method can only be read as a camel case key. Other places can only be used
$my _post->mypostinfo;
To ensure that there is no problem.
The above describes the Laravel Association model because of the name consistency caused by the problem, including the laravel aspects of the content, I hope that the PHP tutorial interested in a friend helpful.