【问题标题】:laravel many to many relationship in this case在这种情况下,laravel 多对多关系
【发布时间】:2014-07-22 02:09:50
【问题描述】:

这个官方例子我已经查过了http://laravel.com/docs/eloquent#many-to-many-polymorphic-relations

但我仍然感到困惑,因为我可能有不同的情况。

我有一个处理details_attribute 表的DetailsAttribute 模型。

我有一个Action 模型女巫处理action 表。

它们之间的关系是多对多的。

所以我用模型DetailsAttributeAction创建了一个新表details_attribute_action

我的DetailsAttribute 模型应该有:

public function actions(){}

我的Actions 模型应该有:

public function detailsAttributes(){}

我的DetailsAttributeAction 模型应该有功能,但我不知道它们是什么。

我的问题是之前函数中的代码是什么? DetailsAttributeAction 真的应该有没有的功能吗?

【问题讨论】:

  • 关系中的函数名称不遵循任何特定规则。你看过文档吗? [laravel.com/docs/eloquent#many-to-many]
  • @revo 是的,我做到了,但在文档中有 4 个模型、视频、标签、博客和可标记但在我的情况下我有 3 个
  • DetailsAttributeAction 型号是什么?
  • 你指的是多态m-m关系。您确定需要这种关系,还是只是简单的多对多关系?
  • @revo 是打破many to many 关系的模型

标签: php laravel laravel-4


【解决方案1】:

您正在寻找的是多对多关系,而不是多态关系。
http://laravel.com/docs/eloquent#many-to-many

您的代码应如下所示:

class DetailsAttribute extends Eloquent {
    // ...

    public function actions()
    {
        // Replace action_id and details_attribute_id with the proper
        // column names in the details_attribute_action table
        return $this->belongsToMany('Action', 'details_attribute_action', 'details_attribute_id', 'action_id');
    }
}

class Action extends Eloquent {
    // ...

    public function detailsAttributes()
    {
        return $this->belongsToMany('DetailsAttribute', 'details_attribute_action', 'action_id', 'details_attribute_id');
    }
}

您不必担心如何在 Laravel 中创建 DetailsAttributeAction 模型。它只是一个映射您创建的多对多关系的表。

【讨论】:

  • @deczo 你是什么意思?请问您说的是哪个型号?
  • 在@Nebez 的两个例子中。
  • @deczo 嘿,你是对的。让我现在更新一下。感谢您指出。
猜你喜欢
  • 1970-01-01
  • 2017-07-18
  • 2015-05-20
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多