<?php
namespace app\common\model;

use app\common\model\Document as DocumentModel;
use think\Db;

/**
 * {$TABLE.Comment}
 * Class {$TABLE.Name}
 * @package app\common\model
 */
class DocumentProduct extends Base {


    /**
     * 关联DocumentCategory模型
     * @return \think\model\relation\BelongsTo
     */
    public function document(){
        return $this->belongsTo('document','id','id');
    }

    /**
     * 添加文章
     * @param $data
     */
    public function add_data($data)
    {
        if(!$data){
            return false;
        }
        $documentModel=new DocumentModel();
        $re=true;
        // 启动事务
        Db::startTrans();
        try {
            $data['status']=1;
            $documentResult=$documentModel->add($data);

            if(!$documentResult){
                throw new \Exception('新增文章失败！');
            }
            $content = isset($data['content'])?$data['content']:'';
            //副表
            $re= $this->save([
                'id'      =>  $documentResult,
                'piclist' =>  $data['piclist'],
                'model_no' =>  $data['model_no'],
                'moq' =>  $data['moq'],
                'payment' =>  $data['payment'],
                'place_of_origin' =>  $data['place_of_origin'],
                'delivery_time' =>  $data['delivery_time'],
                'content' =>  $content,
            ]);
            if(!$re){
                throw new \Exception('新增失败！');
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $re=false;
        }
        if(!$re){
            return $re;
        }
        return $documentResult;
    }

    /**
     * 编辑文章
     * @param $data
     */
    public function edit_data($data)
    {
        if(!$data){
            return false;
        }
        $documentModel=new DocumentModel();
        $re=true;
        // 启动事务
        Db::startTrans();
        try {
            $documentResult=$documentModel->edit($data);
            if(!$documentResult){
                throw new \Exception('编辑文章失败！');
            }
            $content = isset($data['content'])?$data['content']:'';
            //副表
            $re= $this->save([
                'piclist' =>  $data['piclist'],
                'model_no' =>  $data['model_no'],
                'moq' =>  $data['moq'],
                'payment' =>  $data['payment'],
                'place_of_origin' =>  $data['place_of_origin'],
                'delivery_time' =>  $data['delivery_time'],
                'content' =>  $content,
            ],['id' =>  $data['id']]);
            if(!$re){
                throw new \Exception('编辑失败！');
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $re=false;
        }
        return $re;
    }
}