有一个 Laravel 模型与 2 个不同的模型有关系

Have a Laravel model have a relationship with 2 different models

到目前为止,我的设置是一个客户联系门户,并且有一个组织、联系人和注释模型。一个联系人属于一个组织,一个组织有很多联系人。我对此没有问题,但是我在尝试绑定 Notes 模型以便能够与组织和联系人建立关系时遇到问题。基本上这样我就可以在组织上留下注释,但也可以在联系人上留下另一个注释,并且能够搜索属于给定联系人或组织的注释。

我首先想到了一个存储模型 ID 和模型类型的数据透视表 table。我认为哪个与多态枢轴 table 相同?但是我还没有玩过,不知道从哪里开始。

枢轴 table 是这样做的方法吗?或者有没有更简单的方法,这样我的数据库中就没有额外的 table 了?

你可以尝试使用Polymorphic Relations.

来自文档:

Table Structure

Polymorphic relations allow a model to belong to more than one other model on a single association. For example, imagine users of your application can "comment" both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios. First, let's examine the table structure required to build this relationship:

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

Two important columns to note are the commentable_id and commentable_type columns on the comments table. The commentable_id column will contain the ID value of the post or video, while the commentable_type column will contain the class name of the owning model. The commentable_type column is how the ORM determines which "type" of owning model to return when accessing the commentable relation.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

在您的情况下,"Comment" 模型对应于您的 "Note" 模型,而其他模型(视频和 Post)对应于您的组织和联系人模型。

试一试。


在关系中,Laravel 不会创建中间 table,您应该使用 Migrations 添加它们。您的笔记 table 至少应包含以下字段:

- id:(或note_id)table.
的键 - notable_id:表示组织或联系人的外键。
- notable_type: 表示 Note 对象所引用的模型。 (所以前面的字段知道 table 应该寻找正确的对象)。
- 其余的注释字段,例如 titledescription ...