php - 解释 Eloquent morph 很多参数

标签 php laravel eloquent

我是 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/

    相关文章:

    mysql - Laravel 嵌套选择 + MySQL

    php - 按降序排列并返回用于排名的记录号

    php - 如何允许用户在 strip 中输入自定义金额与充电设置金额?

    php - 如何在 Yii for Postgres 中将 float 绑定(bind)到 SQL 命令?

    php - 发现意外数据。尾随数据

    php - 拉拉维尔 : BadMethodCallException Method [show] does not exist

    laravel - 无法连接到GetCandy内的ElasticSearch

    php - 使用 Laravel 返回一对多 Eloquent 关系中的最后一条记录

    php - 在大型项目中使用 MySQL——是否有多个数据库?

    php - 如何在 laravel 的 if 语句中显示值