I am new to laravel, can someone explain to me the parameters of morphMany:
$this->morphMany(Photo::class, 'imageable');
with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.
A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.
Many to Many relations is one of the eloquent relationships in Laravel. The main factor in many many relations is the to join table that is called the pivot table. The pivot table has the ability to perform relations from one model to many models.
The MorphMany relationship has the following function signature:
public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
{
//
}
Where:
$related
(required): refers to the related model. e.g: User::class
.$name
(required): the name of the polymorphic relation, like commentable
.$type
(optional): customize the {relation}_type
field to look up when doing a query.$id
(optional): customize the {relation}_id
field to look up when doing a query.$localKey
(optional): customize the local key (by default id
) to search when doing a query.So -using the example shown in the Laravel documentation- if you want to use a different table structure for the comments
table from this:
posts
id - integer
title - string
body - text
videos
id - integer
title - string
url - string
comments
id - integer
body - text
commentable_id - integer
commentable_type - string
to this:
posts
id - integer
title - string
body - text
videos
id - integer
title - string
url - string
comments
id - integer
body - text
foo - integer // the index to look
bar - string // the type to match
You'd need to define your relationships like this:
Post.php
public function comments()
{
return $this->morphMany(Comment::class, 'commentable', 'foo', 'bar');
}
Video.php
public function comments()
{
return $this->morphMany(Comment::class, 'commentable', 'foo', 'bar');
}
Comment.php
public function commentable()
{
return $this->morphTo('commentable');
}
Check this other answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With