AndrewMcLagan
AndrewMcLagan

Reputation: 13987

Creating polymorphic Many to Many relations in Laravel 4

Im needing to create polymorphic Many-to-Many relations in laravel 4 and im not entirely sure if this is possible.

e.g.

TagModel
 - id
 - title
 - slug

PostModel
 - id
 - title
 - slug
 - content

 PageModel
  - id
  - title
  - slug
  - content

this would of course have tags_tagable pivot table as such

 tags_tagable
  - tag_id
  - tagable_id
  - tagable_type

Upvotes: 2

Views: 1359

Answers (2)

Gravy
Gravy

Reputation: 12445

Laravel 4.1 now has support for polymorphic many to many relationships.

Example below shows how I have implemented sharing Photos with both Products and Posts.

DB Schema

photos

id              integer
filename        string
alt             string

photoable

id              integer
photoable_id    integer
photoable_type  string

Models

Photo Model

class Photo extends Eloquent
{
public function products(){
    return $this->morphedByMany('Product', 'photoable');
}

public function posts(){
    return $this->morphedByMany('Post', 'photoable');
}
}

Product Model

class Product extends Eloquent
{
public function photos(){
    return $this->morphToMany('Photo', 'photoable');
}
}

Post Model

class Post extends Eloquent
{
public function photos(){
    return $this->morphToMany('Photo', 'photoable');
}
}

With the above, I can access all photos which are attached to a product as follows:

$product = Product::find($id);
$productPhotos = $product->photos()->all();

I can also iterate over to display all photos as any collection of models.

foreach ($productPhotos as $photo)
{
    // Do stuff with $photo
}

The above can be replicated almost exactly to your requirements with a few model name changes.

Upvotes: 0

Laurence
Laurence

Reputation: 60048

Polymorphic many to many relationships will be released in Laravel 4.1 in November.

You could try and switch to the 4.1 branch and use them now if you want. But at this stage I've not seen any specific documentation on their use - only the tweet from Taylor.

See tweet here

Upvotes: 3

Related Questions