Search code examples
phplaravellaravel-5eloquentlaravel-relations

How does Laravel resolve some methods in models?


I wanna know how laravel can find and how it work some method like realtions method

(1:1 & 1:M )


for e.g in User Model i have one to many relation with My Post Model

public function posts(){
return $this->hasMany(Post::class);
}

and when i want to get some user posts data i will use this code

$user = User::find(1);
$user->posts();

here is my question $user->posts(); how laravel can find and reslove it


Solution

  • hasMany is just one of the relationships that Eloquent provides for fluent querying to the database. With the correct column and table names, using these relationships, you can easily build a logical structure without having to dive into complex queries.

    When you use a hasMany, Eloquent knows that the model you query on can have an n amount of related models, and will return a collection. It knows how to query using the model and method names. So, since your user has the hasMany for posts, Eloquent will query on user_id on the posts table.

    For example, when you dump a query log on a hasMany, it will return the following:

    select * from `posts` where `posts`.`user_id` in (1)

    Eloquent will automatically append this to your model if you eager load it: User::with('posts')->find(1)

    I suggest reading the docs on relationships to figure out what Laravel and Eloquent assume to build queries.