因为很熟悉DJANGO,所以对TP,要慢慢适应。

1,SQL文件

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50505
Source Host           : localhost:3306
Source Database       : thinkphp_inaction

Target Server Type    : MYSQL
Target Server Version : 50505
File Encoding         : 65001

Date: 2019-06-23 20:03:30
*/

;

-- ----------------------------
-- Table structure for c5_post
-- ----------------------------
DROP TABLE IF EXISTS `c5_post`;
CREATE TABLE `c5_post` (
  `post_id` ) unsigned NOT NULL AUTO_INCREMENT,
  `title` ) NOT NULL,
  `content` text NOT NULL,
  `created_at` ) NOT NULL,
  `updated_at` ) NOT NULL,
  `) NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of c5_post
-- ----------------------------
');
');

-- ----------------------------
-- Table structure for c5_user
-- ----------------------------
DROP TABLE IF EXISTS `c5_user`;
CREATE TABLE `c5_user` (
  `id` ) NOT NULL AUTO_INCREMENT,
  `username` ) NOT NULL,
  `password` ) NOT NULL,
  `created_at` ) NOT NULL,
  `updated_at` ) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `username` (`username`) USING BTREE
) ENGINE DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of c5_user
-- ----------------------------
');

-- ----------------------------
-- Table structure for c5_user_extra
-- ----------------------------
DROP TABLE IF EXISTS `c5_user_extra`;
CREATE TABLE `c5_user_extra` (
  `id` ) NOT NULL AUTO_INCREMENT,
  `email` ) NOT NULL,
  `qq` ) NOT NULL,
  `) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of c5_user_extra
-- ----------------------------
');

2,Application\Common\Conf\config.php

<?php
return array(
    //'配置项'=>'配置值'
    'DB_TYPE' => 'mysql',
    'DB_HOST' => 'localhost',
    'DB_PORT' => 3306,
    'DB_USER' => 'root',
    'DB_PWD' => 'xxxx',
    'DB_NAME' => 'thinkphp_inaction',
    'DB_PREFIX' => 'c5_'
);

3,Applicaton\Home\Model\UserModel.class.php

<?php
    namespace Home\Model;
    use Think\Model\RelationModel;

    class UserModel extends RelationModel {
        private $denyUserNames = array (
            'admin',
            'administraotr'
        );
        public $_validate = array(
            array('username', 'require', 'user is not empty'),
            array('password', 'require', 'password is not empty', 1, '', 1),
            array('username', '', 'user has existed.', 0, 'unique', 1),
            array('password', '6, 20', 'password length between 6~20', 0, 'length'),
            array('password', '/^\w{6,20}$/', 'password format is error'),
            array('password', 'repassword', 'confirm password is error', 0, 'confirm', 1),
            array('username', 'checkUsername', 'user name is illegal', 0, 'callback'),
        );

        public $_auto = array(
            array('password', 'md5', self::MODEL_BOTH, 'function'),
            array('created_at', 'time', self::MODEL_INSERT, 'function'),
            array('updated_at', 'time', self::MODEL_UPDATE, 'function')
        );

        public $_link = array(
            'extra' => array(
                'mapping_type' => self::HAS_ONE,
                'class_name' => 'UserExtra',
                'foreign_key' => 'user_id',
                'mapping_fields' => 'email, qq'
            ),
            'posts' => array(
                'mapping_type' => self::HAS_MANY,
                'class_name' => 'Post',
                'foreign_key' => 'user_id'
            )
        );

        public function checkUsername($username) {
            foreach ($this->denyUserNames as $u) {
                if (strpos($username, $u) !== false) {
                    return false;
                }
            }
            return true;
        }
    }
?>

4,Applicaton\Home\Model\PostModel.class.php

<?php
/**
 * Created by PhpStorm.
 * User: Sahara
 * Date: 2019/6/23
 * Time: 19:00
 */

namespace Home\Model;
use Think\Model\RelationModel;

class PostModel extends RelationModel {
    public $_link = array(
        'author' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'User',
            'foreign_key' => 'user_id',
        )
    );

}

5,Applicaton\Home\Model\PostViewModel.class.php

<?php
/**
 * Created by PhpStorm.
 * User: Sahara
 * Date: 2019/6/23
 * Time: 19:00
 */

namespace Home\Model;
use Think\Model\ViewModel;

class PostViewModel extends ViewModel {
    public $viewFields = array(
        'Post' => array(
            'post_id',
            'title',
            'content',
            'created_at',
            'updated_at'
        ),
        'User' => array(
            'username' => 'author',
            '_on' => 'Post.user_id=User.id'
        )
    );
}

6,Applicaton\Home\Controller\IndexController.class.php

<?php
namespace Home\Controller;
use Home\Model\PostModel;
use Home\Model\PostViewModel;
use Home\Model\UserModel;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        $user = new UserModel();
        $data = array(
            'username' => 'zhangsan',
            'password' => '111111',
            'repassword' => '111111'
        );
        if (!$user->create($data)) {
            echo $user->getError();
            exit;
        } else {
            $id = $user->add();
            print_r($user->find($id));
        }
        echo 'ok';
    }

    public function posts() {
        $m = new PostViewModel();
        $data = $m->select();
        print_r($data);
    }

    public function posts2() {
        $m = new UserModel();
        $data = $m->relation('extra')->find();
        print_r($data);
    }

    public function posts3() {
        $m = new PostModel();
        $data = $m->relation('author')->find();
        print_r($data);
    }

    public function posts4() {
        $m = new UserModel();
        $data = $m->relation('posts')->find();
        print_r($data);
    }
}

ThinkPHP模型中的HAS_ONE,BELONG_TO,HAS_MANY实践的更多相关文章

  1. thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法)

    thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法) 一.总结 记得看下面 1.获取器的作用是在获取数据的字段值后自动进行处理 2.修改器的作用是可以在数据赋值的时候自动进行转换处 ...

  2. thinkphp在模型中自动完成session赋值

    相信用过thinkphp的用户都知道thinkphp的模型可以完成很多辅助功能,比 如自动验证.自动完成等,今天在开发中遇到自动完成中需要获取session值 然后自动赋值的功能,具体看代码:clas ...

  3. thinkphp模型事件(钩子函数:模型中在增删改等操作前后自动执行的事件)

    thinkphp模型事件(钩子函数:模型中在增删改等操作前后自动执行的事件) 一.总结 1.通过模型事件(钩子函数),可以在插入更新删除等前后执行一些特定的功能 2.模型事件是写在模型里面的,控制器中 ...

  4. [Asp.net MVC]Asp.net MVC5系列——从控制器访问模型中的数据

    目录 概述 从控制器访问模型中的数据 强类型模型与@model关键字 总结 系列文章 [Asp.net MVC]Asp.net MVC5系列——第一个项目 [Asp.net MVC]Asp.net M ...

  5. 错误之thinkphp模型使用发生的错误

    刚接触thinkphp模型的创建,在创建model类时在这里边声明了类的对象.唉,这是不理解的错误啊.什么叫做实例化模型对象,在控制器里边使用才创建. 模型这里写各种用到的函数. 这里我也体会到了查询 ...

  6. thinkphp模型层Model、Logic、Service讲解

    thinkphp模型层Model.Logic.Service讲解 时间:2014-08-24 15:54:56   编辑:一切随缘   文章来源:php教程网 已阅读:771 次       js特效 ...

  7. ThinkPHP 模型(Model)命名规范

    一个小问题搞了好久:如果数据库的表名中有下划线,那么在用thinkphp做自动完成时注意Model类的命名要变成驼峰法,文件名和类名都要变.( 另外注意:只有使用create方法创建数据时才能调用到自 ...

  8. 浅析Thinkphp框架中运用phprpc扩展模式

    浅析Thinkphp框架中应用phprpc扩展模式 这次的项目舍弃了原来使用Axis2做web服务端的 方案,改用phprpc实现,其一是服务端的thinkphp已集成有该模式接口,其二是phprpc ...

  9. 关联模型中如果condition条件

    在练习中,有一个user表和地址表,一对多的关系. 我的想法是,通过这个关联模型找出这个用户下面默认值字段为1的地址 控制器中 public function index(){ $User = D(' ...

随机推荐

  1. 使用Android手机进行开发的尝试

    使用Android手机查看和修改Excel文件.PowerPoint文件并连接幻灯机进行演示等办公方式想必大家已经有所了解.今天介绍一下怎样使用Android进行软件开发. Termux 使用Andr ...

  2. 湖南省第6届程序大赛第6题 Biggest Number

    Problem F Biggest Number You have a maze with obstacles and non-zero digits in it: You can start fro ...

  3. centos 分区挂载准备工作

    -bash: wget: command not found的两种解决方法 yum安装 yum -y install wget mount: unknown filesystem type 'ntfs ...

  4. 【LOJ523】[LibreOJ β Round #3]绯色 IOI(悬念)(霍尔定理_基环树)

    题目 LOJ523 官方题解 分析 由于某些原因,以下用「左侧点」和「右侧点」分别代替题目中的「妹子」和「男生」. 根据题意,显然能得出一个左侧点只能向一个或两个右侧点连边.这似乎启发我们把左侧点不看 ...

  5. SET key value [EX seconds] [PX milliseconds] [NX|XX]

    SET key value [EX seconds] [PX milliseconds] [NX|XX] 可用版本: >= 1.0.0 时间复杂度: O(1) 将字符串值 value 关联到 k ...

  6. 嵌入式02 STM32 实验11 NVIC和中断总结

    一.基础知识 1.cortex-m3支持256个中断,其中包含了16个内核中断,240个外部中断 2.STM32只有84个中断,包括16个内核中断和68个可屏蔽中断 3.STM32F103上只有60个 ...

  7. 读文件时出现这个错误 'utf-8' codec can't decode byte 0xba in position 21: invalid start byte

    ''' file2 文件内容: 很任性wheniwasyoung ''' 源代码: f = open("file2",'r',encoding="utf-8") ...

  8. Python3 - 数字类型

    在 Python 中,数字并不是一个真正的对象类型,而是一组类似类型的分类.Python 不仅支持通常的数字类型(整数和浮点数),而且还能够通过常量去直接创建数字以及处理数字的表达式.数字数据类型是不 ...

  9. PAT(B) 1030 完美数列 - C语言 - 滑动窗口 & 双指针

    题目链接:1030 完美数列 (25 point(s)) 给定一个正整数数列,和正整数 \(p\),设这个数列中的最大值是 \(M\),最小值是 \(m\),如果 \(M≤mp\),则称这个数列是完美 ...

  10. 快速排序(Quick Sort)C语言

    已知数组 src 如下: [5, 3, 7, 6, 4, 1, 0, 2, 9, 10, 8] 快速排序1 在数组 src[low, high] 中,取 src[low] 作为 关键字(key) . ...