多対多で一方向にポリモーフィックないくつかのモデル間の関係が欲しいです。これが今のところ解決した方法ですが、このようにするのは本当に面倒です。すべての attach() を失います。 detach() などの機能であり、これを行う簡単な方法である必要があります。ドキュメント、例などが見つかりません。私が見たのはとても基本的なものだけです。
<?php
use Illuminate\Database\Eloquent\Collection;
class Category extends Eloquent {
/*
public function categorizables() {
return $this->morphTo();
}
*/
public function categorizables(){
$categorizables = new Collection();
$categorizableRows = DB::table('categorizables')->where('category_id', $this->id)->get();
foreach ($categorizableRows as $categorizable) {
$class = $categorizable->categorizable_type;
$categorizables->add($class::find($categorizable->categorizable_id));
}
return $categorizables;
}
}
class Article extends Eloquent {
/*
public function categories() {
return $this->morphMany('Category','categorizable');
}
*/
public function categories(){
$categoryRows = DB::table('categorizables')
->where('categorizable_id', $this->id)
->where('categorizable_type', get_class($this))->get();
$categoryIds = array();
foreach ($categoryRows as $category) {
$categoryIds[] = $category->id;
}
return Category::find($categoryIds);
}
}
class Person extends Eloquent {
/*
public function categories() {
return $this->morphMany('Category','categorizable');
}
*/
public function categories(){
$categoryRows = DB::table('categorizables')
->where('categorizable_id', $this->id)
->where('categorizable_type', get_class($this))->get();
$categoryIds = array();
foreach ($categoryRows as $category) {
$categoryIds[] = $category->id;
}
return Category::find($categoryIds);
}
}
/*
Table categorizables
id
category_id
categorizable_type (Possible "Article" or "Person" in this case)
categorizable_id (id of Article or Person)
Table categories
id
name
Table articles
id
name
content
Table People
id
name
content
*/