我想要几个模型之间的关系,这个模型是多对多的,并且在一个方向上是多态的,这就是我现在解决它的方式,但是我真的很烦我这样做,我放松所有附件(),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
*/