Home  >  Article  >  Backend Development  >  Laravel association model problems caused by name consistency laravel video tutorial thinkphp php laravel

Laravel association model problems caused by name consistency laravel video tutorial thinkphp php laravel

WBOY
WBOYOriginal
2016-07-29 08:50:021496browse

1. Define the association model

In Laravel, we can complete the association query by defining the following Model.

class MyPost extends Eloquent {
    public function myPostInfo () {
        return $this->hasOne('MyPostInfo');
    }
}

class MyPostInfo extends Eloquent {}

2. Use the association model

HeremyPostInfo() uses Camel naming rules, but we can use Snake rules when reading a certain PostInfo. The following code is feasible:

$post = MyPost::find(1);
$post_info = $post->myPostInfo; // example 1
$post_info = $post->my_post_info; // example 2

Laravel allows the above two methods, but does not reasonably handle the conflict caused by using the two naming methods.

3. Cache invalidation

If we use the above two examples at the same time, one of the caches will be invalidated. In the relationships variable of the Model, the related Model that has been read is cached, but when we read it with a name with different rules, the previous cache will be invalidated. 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 expire, you have to use only one naming method in the project to read the relational model. Laravel recommends Camel Case.

4. The toArray() method is invalid

If both are used at the same time, another problem is that Model::toArray() is invalid. Because the toArray() method first looks for the association model named Snake Case in relations, and if not, then looks at the Camel Case.

So if you use the toArray() method to convert the Model, do not use both at the same time.

5. Easy-to-make mistakes

The most easy-to-make code is this:

MyPost::with(‘myPostInfo’)->get();

When using With to eagerLoad to associate the model, you must use the key with the same name as the definition method to read, so how to read it like this It can only be the key of Camel Case. In other places, you can only use

$my_post->myPostInfo;

to ensure there are no problems.

The above introduces the problems caused by name consistency in Laravel's association model, including laravel content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn