如何创建"发布" MVC中的模型与关系数据库?

时间:2015-06-06 12:47:56

标签: php model-view-controller model relationship

我的" mvc_posts"表

  • id(int)
  • title(varchar)
  • CATEGORY(varchar) - >例如:1,2,3
  • url(varchar)

我的" mvc_categories"表

  • id(id)
  • name(varchar)

我的帖子模型类:

class Post extends Database{

    protected $table = 'mvc_posts';

    public function __construct(){
        $this->db = new Database;
    }

    public function viewByUrl($url){

        $obj = array();
        $where = array('url' => $url);
        $obj = $this->db->select("*", $this->table, $where);
        if($obj == true){

            $obj->category_name = $this->category->getName($obj->category);
            return $obj;

        }

    }

}

我的类别模型类:

class Category extends Database{

    protected $table = 'mvc_categories';

    public function __construct(){
        $this->db = new Database;
    }

    public function getName($category){

        $categories = explode(",", $category);
        $category_name = "";

        foreach($categories as $key => $value){

            $where = array('id' => $value);
            $category = $this->db->select("*", $this->table, $where);
            $category_name .= $category->name.', ';

        }
        return rtrim($category_name, ', ');

    }

}

如何在Post类中使用类Category的getName()方法?

1 个答案:

答案 0 :(得分:0)

最简单的方法是将Category模型作为参数传递给Post :: viewByUrl()

尽管如此,大多数框架都实现了某种形式的依赖注入。你在使用框架吗?