In this case, the Phone model is automatically assumed to have a user_id foreign key. Dynamic properties allow you to access relationship methods as if they were properties defined on the model: $phone = User::find(1)->phone Įloquent determines the foreign key of the relationship based on the model name. Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. The first argument passed to the hasOne method is the name of the related model. The phone method should call the hasOne method and return its result: hasOne('App\Models\Phone') To define this relationship, we place a phone method on the User model. For example, a User model might be associated with one Phone. One To OneĪ one-to-one relationship is a very basic relation. Relationship names cannot collide with attribute names as that could lead to your model not being able to know which one to resolve. For example, we may chain additional constraints on this posts relationship: $user->posts()->where('active', 1)->get() īut, before diving too deep into using relationships, let's learn how to define each type. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. Eloquent makes managing and working with these relationships easy, and supports several different types of relationships:Įloquent relationships are defined as methods on your Eloquent model classes. For example, a blog post may have many comments, or an order could be related to the user who placed it. Aggregating Related Models On Polymorphic Relationshipsĭatabase tables are often related to one another.Defining Custom Intermediate Table Models.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |