Php laravel 4数据透视表错误

Php laravel 4数据透视表错误,php,laravel-4,many-to-many,Php,Laravel 4,Many To Many,我有下列表格 cards - id - name - ... types - id - name - ... cards_types - card_id - type_id - ... 我正试图建立一种多对多的关系: class Type extends \Eloquent { public function cards() { return $this->hasManyThrough('\App\Models\Ca

我有下列表格

cards
  - id
  - name
  - ...

types
  - id
  - name
  - ...

cards_types
  - card_id
  - type_id
  - ...
我正试图建立一种多对多的关系:

class Type extends \Eloquent
{
    public function cards()
    {
        return $this->hasManyThrough('\App\Models\Card', '\App\Models\Type', 'card_id', 'type_id');
    }
}


class Card extends \Eloquent
{
    public function subtypes()
    {
        return $this->hasManyThrough('\App\Models\Type', '\App\Models\CardType', 'type_id', 'card_id');
    }
}

class CardType extends \Eloquent
{
    /**
     * The database table used by the model.
     * @var string
     */
    protected $table = 'cards_types';
}
要向我的卡片添加许多子类型,请执行以下操作:

$card_id = 1;
$subtypes_ids = array(1,2,3,4);
$card = Card::find($card_id);
$card->subtypes()->add($subtypes_ids);
但是我得到了以下错误

[Illuminate\Database\QueryException]
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cards_types.id' in 'on clause' (SQL: select `types`.*, `cards_types`.`type_id` from `types` in ner join `cards_types` on `cards_types`.`id` = `types`.`card_id` where `cards_types`.`type_id` = 21)
我不知道“id”是在哪里找到的…,我也尝试过这个(结果相同):

编辑


我成功地将hasManyThrough更改为回答的belongsTo方法,使我的关系正常运行,但我想了解我的解决方案与此解决方案之间的区别,有人能帮我吗?

实现上面概述的正确方法实际上是使用BelongToMany关系,因为这是为中间数据透视表纯粹作为提供两个模型之间的多对多链接的一种方式而存在的实例而设计的,并且您已经切换到这种关系类型你的问题

hasManyThrough是为您希望通过另一个中间关系表定义关系而设计的,而不是像在

在本例中,没有直接的数据透视表,每个数据透视表都表示一个特定的模型,但用户模型数据透视表充当一个数据透视表,通过该数据透视表可以建立从国家到邮政的关系。当您尝试在示例中使用hasManyThrough时,Elount将card_types视为一个模型表,该模型表应具有自己的唯一id以进行连接,因此出现“未知列'cards_types.id'”错误

这就是我对它的理解——我不确定这是否会让你明白


格伦

谢谢你的解释,现在更清楚了:)我仍然对透视表有一个小问题,我的卡绑定到许多类型,如前所述,它们有“元类型”(比如类型{名称:生物,类型:超级类型}),是否可以在卡模型中创建两个方法($card->types(),$card->supertypes())将卡链接到同一个表但被“过滤”的方法?您可以尝试通过显式重写关联键来添加共享同一透视表的两个关系,例如$this->belongToMany('Type'、'cards\u types'、'card\u id'、'Type\u id');和$this->belongtomany('Type'、'cards_types'、'card_id'、'super_Type_id');-我还没有尝试过这个,但理论上它应该可以工作。另外,请看一下文档的“急切加载”部分,在“急切加载约束”部分下,可以找到一种在加载关系时应用约束/过滤器的方法。
$card_id = 1;
$card = Card::find($card_id);
var_dump($card->subtypes()->get());