ThinkPHP模型中的HAS_ONE,BELONG_TO,HAS_MANY实践

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThinkPHP模型中的HAS_ONE,BELONG_TO,HAS_MANY实践相关的知识,希望对你有一定的参考价值。

因为很熟悉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
*/

SET FOREIGN_KEY_CHECKS=0;

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

-- ----------------------------
-- Records of c5_post
-- ----------------------------
INSERT INTO `c5_post` VALUES (1, post1title, 1content, 0, 0, 2);
INSERT INTO `c5_post` VALUES (2, post2title, 2content, 0, 0, 2);

-- ----------------------------
-- Table structure for c5_user
-- ----------------------------
DROP TABLE IF EXISTS `c5_user`;
CREATE TABLE `c5_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(40) NOT NULL,
  `password` char(32) NOT NULL,
  `created_at` int(10) NOT NULL,
  `updated_at` int(10) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `username` (`username`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of c5_user
-- ----------------------------
INSERT INTO `c5_user` VALUES (2, zhangsan, 96e79218965eb72c92a549dd5a330112, 1561283445, 0);

-- ----------------------------
-- Table structure for c5_user_extra
-- ----------------------------
DROP TABLE IF EXISTS `c5_user_extra`;
CREATE TABLE `c5_user_extra` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(40) NOT NULL,
  `qq` char(20) NOT NULL,
  `user_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of c5_user_extra
-- ----------------------------
INSERT INTO `c5_user_extra` VALUES (3, [email protected], 9409620, 2);

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‘, ‘/^\\w6,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实践的主要内容,如果未能解决你的问题,请参考以下文章

使用thinkphp 关联模型has_one插入数据问题:插入数据的时候只操作一张表为啥?

Rails validates_presence_of 并验证 has_one 关联模型中的存在

thinkphp关联模型 condition关联条件怎么用,能说个例子吗

Rails:在父模型的视图中创建一个 has_one 模型?

Rails 中具有相同键的两个表而不是 has_one 关系

Rails API 将 has_one: 图像从模型项推送到 Cloudinary 但不能