1

我想要几个模型之间的关系,它是多对多的,并且在一个方向上是多态的,这就是我现在解决它的方法,但这样真的很困扰我,我失去了所有的附加(), 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
*/
4

0 回答 0