TP5關聯模型 一對多 字段別名 easyui tree

一、模型

1.生產計劃。包括年月日 

class Plan extends Model
{
    protected $table = 'tplan';
    protected $pk = 'rd';
    public function children() { //建立一對多關聯
        return $this->hasMany('PlanProduct','plan_id','rd');->field('rd,plan_id,plan_id  as id, product_id as text');//必須包含主鍵rd
    }//end function children
}
2.生產計劃中的產品。需要生產的產品列表

class PlanProduct extends Model
{
    protected $table = 'tplanproduct';
    protected $pk = 'rd';

    public function children() {

        //建立一對一關聯 讓被關聯的字段附在主錶行上返回
        return $this->hasOne('Product','id','product_id')->bind([
                'text' =>'name',
                'id',
            ]);
    }//end function children
}

3.產品表

class Product extends Model
{
    protected $table = 'tproduct';
    protected $pk = 'rd';
}

二、控制器調用  

$list = Plan::with(['children','children.children'])
      ->Distinct(true)->field('nweek  as id, nweek  as text,nyear,nmonth,rd')
      ->order(['nyear'=>'desc','nmonth'=>'desc','nweek'=>'desc'])
      ->where(['nyear'=>'2019','nmonth'=>'3'])
      ->select();
      // dump($list);
      echo $list->toJson();

三、在瀏覽器上顯示的結果

array(2) {
  [0] => array(6) {
    ["id"] => int(2)
    ["text"] => int(2)
    ["nyear"] => int(2019)
    ["nmonth"] => int(3)
    ["rd"] => int(7)
    ["children"] => array(0) {
    }
  }
  [1] => array(6) {
    ["id"] => int(1)
    ["text"] => int(1)
    ["nyear"] => int(2019)
    ["nmonth"] => int(3)
    ["rd"] => int(6)
    ["children"] => array(2) {
      [0] => array(9) {
        ["rd"] => int(1)
        ["plan_id"] => int(6)
        ["product_id"] => string(2) "01"
        ["order_quantity"] => int(10)
        ["order_time"] => int(0)
        ["start_time"] => int(0)
        ["end_time"] => int(0)
        ["text"] => string(5) "QTZ63"
        ["id"] => string(2) "01"
      }
      [1] => array(9) {
        ["rd"] => int(2)
        ["plan_id"] => int(6)
        ["product_id"] => string(2) "02"
        ["order_quantity"] => int(0)
        ["order_time"] => int(0)
        ["start_time"] => int(0)
        ["end_time"] => int(0)
        ["text"] => string(3) "120"
        ["id"] => string(2) "02"
      }
    }
  }
}

[{"id":2,"text":2,"nyear":2019,"nmonth":3,"rd":7,"children":[]},{"id":1,"text":1,"nyear":2019,"nmonth":3,"rd":6,"children":[{"rd":1,"plan_id":6,"product_id":"01","order_quantity":10,"order_time":0,"start_time":0,"end_time":0,"text":"QTZ63","id":"01"},{"rd":2,"plan_id":6,"product_id":"02","order_quantity":0,"order_time":0,"start_time":0,"end_time":0,"text":"120","id":"02"}]}]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章