【问题标题】:How to create "post" model in MVC with relationship database?如何使用关系数据库在 MVC 中创建“发布”模型?
【发布时间】:2015-08-21 09:05:42
【问题描述】:

我的“mvc_posts”表:

  • id (int)
  • 标题(varchar)
  • CATEGORY (varchar) -> 示例:1,2,3
  • 网址(varchar)

我的“mvc_categories”表:

  • id (id)
  • 名称(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;

        }

    }

}

我的 Category 模型类:

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() 方法?

【问题讨论】:

    标签: php model-view-controller model relationship


    【解决方案1】:

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

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

    【讨论】:

    • 您好,感谢您的回复。我正在使用我自己的框架。我会理解这种情况的运行逻辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2018-07-31
    • 2018-06-24
    • 1970-01-01
    相关资源
    最近更新 更多