Laravel 4.1 では、ポリモーフィックな多対多の関係がサポートされるようになりました。
以下の例は、製品と投稿の両方で写真を共有する方法を実装した方法を示しています。
DB スキーマ
写真
id integer
filename string
alt string
撮影可能
id integer
photoable_id integer
photoable_type string
モデル
写真モデル
class Photo extends Eloquent
{
public function products(){
return $this->morphedByMany('Product', 'photoable');
}
public function posts(){
return $this->morphedByMany('Post', 'photoable');
}
}
製品モデル
class Product extends Eloquent
{
public function photos(){
return $this->morphToMany('Photo', 'photoable');
}
}
投稿モデル
class Post extends Eloquent
{
public function photos(){
return $this->morphToMany('Photo', 'photoable');
}
}
上記で、次のように製品に添付されているすべての写真にアクセスできます。
$product = Product::find($id);
$productPhotos = $product->photos()->all();
また、モデルのコレクションとしてすべての写真を表示するために繰り返し処理することもできます。
foreach ($productPhotos as $photo)
{
// Do stuff with $photo
}
上記は、モデル名を少し変更するだけで、要件にほぼ正確に複製できます。