TP5一對一、一對多關聯模型的使用


控制器:

namespace app\admin\controller;
use app\admin\model\Article ;
use think\Controller;
use think\Db;

/**
 * 關於TP5一對一/一對多關聯的關聯查詢
 * Class Member
 * @package app\admin\controller
 */
class Guser extends Controller
{
    public function index()
    {
        //查詢所有每篇文章下的評論內容且分頁
        $article_list = Article::with('comment')->order('add_time asc')->field('id,title,add_time,introduction,clicknum')->paginate(20)->toArray();
        dump($article_list);exit;
    }
}

模型Article.php

/**
 * 主表(tp_article)的模型
 * Class Article
 * @package app\admin\model
 */
class Article extends Model
{
    /**
     * 一對多
     * 建立和tp_comment表的關聯
     * hasMany方法的參數包括:hasMany('關聯模型名','外鍵名','主鍵名',['模型別名定義']);
     * gg_id 是關聯表的關聯鍵名
     * clicknum 是主表的被關聯的鍵名
     */
    public function comment()
    {
        return $this->hasMany('comment','gg_id','clicknum');
    }

    /**
     * 一對一
     * 建立和tp_comment表的關聯
     * hasMany方法的參數包括:hasMany('關聯模型名','外鍵名','主鍵名',['模型別名定義']);
     * gg_id 是關聯表的關聯鍵名
     * clicknum 是主表的被關聯的鍵名
     */
    public function comment()
    {
        return $this->hasOne('comment','gg_id','clicknum');
    }
}

模型Comment.php

/**
 * tp_comment 表模型
 * @package app\admin\model
 */
class Comment extends Model
{
    /**
     * 建立和tp_article表(主表)的關聯
     * belongsTo的參數包括::belongsTo('關聯模型名','外鍵名','關聯表主鍵名',['模型別名定義'],'join類型');
     */
    public function article()
    {
        return $this->belongsTo('article');
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM