我有以下表格
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”是在哪里找到的.,我也尝试过这样做(结果相同):
$card_id = 1;
$card = Card::find($card_id);
var_dump($card->subtypes()->get());编辑
我成功地使我的关系成功地改变了hasManyThrough和2 belongsTo方法作为应答here,但是我想了解我的解决方案和这个解决方案之间的区别,有人能帮我吗?
发布于 2014-01-09 10:53:47
实现上述目标的正确方法实际上是使用belongsToMany关系,因为这是为中间枢轴表存在的情况而设计的,它纯粹是为了在两个模型之间提供多到多个链接的一种方式--并且在创建时切换到这种关系类型可以解决您的问题。
hasManyThrough是为您希望通过另一个表定义关系的实例而设计的,该表是一个中间关系,而不是使用直枢轴表,如在http://laravel.com/docs/eloquent#has-many-through文档中给出的示例。
在这个例子中,没有直接的枢轴表,每个表都代表一个特定的模型--但是用户模型表充当了一个支点,通过它建立了从国家到岗位的关系。当您试图在示例中使用hasManyThrough时,雄辩的观点是将card_types视为一个模型表,该表应该有自己的唯一id来进行连接,因此出现了“未知列'cards_types.id'”错误。
这就是我对它的理解--不确定这是否为你清除了任何东西。
格伦
https://stackoverflow.com/questions/21014372
复制相似问题