rainbowrefa.blogg.se

Eloquent model
Eloquent model





eloquent model

In the example above, Eloquent will try to match the user_id from the Phone model to an id on the User model. We can define the inverse of a hasOne relationship using the belongsTo method: belongsTo('App\User')

eloquent model eloquent model

Now, let's define a relationship on the Phone model that will let us access the User that owns the phone. So, we can access the Phone model from our User. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key: return $this->hasOne('App\Phone', 'foreign_key', 'local_key') In other words, Eloquent will look for the value of the user's id column in the user_id column of the Phone record. If you wish to override this convention, you may pass a second argument to the hasOne method: return $this->hasOne('App\Phone', 'foreign_key') Īdditionally, Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In this case, the Phone model is automatically assumed to have a user_id foreign key. Dynamic properties allow you to access relationship functions 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\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.

#Eloquent model how to#

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.Ī one-to-one relationship is a very basic relation. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as functions 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 functions 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. Dynamic Propertiesĭatabase tables are often related to one another.







Eloquent model