Question

I have the following tables

cards
  - id
  - name
  - ...

types
  - id
  - name
  - ...

cards_types
  - card_id
  - type_id
  - ...

and i'm trying to setup a many to many relationship:

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';
}

and to add many subtypes to my card like this:

$card_id = 1;
$subtypes_ids = array(1,2,3,4);
$card = Card::find($card_id);
$card->subtypes()->add($subtypes_ids);

but I get the following error

[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)

and I don't get where the 'id' is found..., I've also tried this (with same result):

$card_id = 1;
$card = Card::find($card_id);
var_dump($card->subtypes()->get());

EDIT

I've suceeded in making my relationship works by changing the hasManyThrough with 2 belongsTo method as answered here, but i'd like to understand the difference between my solution and this one, someone can help me ?

Was it helpful?

Solution

The correct way to achieve what you outline above is in fact with the belongsToMany relationship as this is designed for instances where the intermediate pivot table exists purely as a means of providing the many to many links between the two models - and as you have founding switching to this relationship type fixes your problem.

The hasManyThrough is designed for instances where you are wanting to define the relationship through another table that is an intermediate relation, rather than using a straight pivot table, as in the example given in the docs at http://laravel.com/docs/eloquent#has-many-through

In this example there is no straight pivot table, each table represents a specific model - but the user model table acts as a pivot through which the relationships from countries to posts is made. When you tried to use hasManyThrough in your example eloquent was seeing card_types as a model table that should have its own unique id to make the join on, hence "the Unknown column 'cards_types.id'" error.

That is how I understand it anyway - not sure if that clears it up any for you.

Glen

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top