我是 Laravel 的新手,有人可以向我解释 morphMany 的参数:
$this->morphMany(Photo::class, 'imageable');
最佳答案
MorphMany关系具有以下函数签名:
public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
{
//
}
在哪里:
$related
( 需要 ):指相关模型。例如:User::class
. $name
( 需要 ):多态关系的名称,如 commentable
. $type
(可选):自定义 {relation}_type
进行查询时要查找的字段。 $id
(可选):自定义 {relation}_id
进行查询时要查找的字段。 $localKey
(可选):自定义本地键(默认为 id
)进行查询时进行搜索。 所以 - 使用 example shown in the Laravel documentation - 如果您想为
comments
使用不同的表结构从这个表: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
对此:
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
你需要像这样定义你的关系:
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');
}
评论.php
public function commentable()
{
return $this->morphTo('commentable');
}
检查这个 other answer .
关于php - 解释 Eloquent morph 很多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235721/