Php Laravel框架 多表關系處理 之 Eloquent一對多關系處理
? ? ? ? 本博文主要介紹 Laravel 框架中 Eloquent ?對一對多關系的處理以及在?Laravel Administrator(后臺擴展包)中的應用。
? ? ? ? 您的數據庫可能是彼此相關的。比方,一篇博客文章可能有很多評論,或者一個訂單與下訂單的用戶相關。Eloquent 使得管理和處理這些關系變得簡單。Laravel 提供了四種類型的關系: -一對一 -一對多 -多對多 - 多態關系
? ? ? 一對多
一個一對多關系的樣例是一篇博客文章有很多評論或者一個課程有的多次分數信息等。
我們能夠像這樣定義關系模型 Model:
<?php
/*** sobjectinfo:課程信息表 Model* soc_id :主鍵自增* soc_name :課程名* soc_teacher:授課老師**/
class SobjectInfo extends Eloquent {//自己定義表名(protected $table)protected $table = 'sobjectinfo';//自己定義主鍵(protected $primaryKey)protected $primaryKey = 'soc_id';//關閉 創建時間 與 更新時間 的自己主動維護(protected $timestamps)public $timestamps = false;/** 定義一對多關系*/public function Scoreinfo(){return $this -> hasMany('Scoreinfo','soc_id');}
}?>
定義與之相應的逆向關系 Model:
<?php
/*** scoreinfo:分數信息表 Model* so_id :主鍵自增* s_id :學生信息表(stuinfo)主鍵* soc_id :課程信息表(sobjectinfo)主鍵* score :分數*/
class ScoreInfo extends Eloquent {//自己定義表名(protected $table)protected $table = 'scoreinfo';//自己定義主鍵(protected $primaryKey)protected $primaryKey = 'so_id';//關閉 創建時間 與 更新時間 的自己主動維護(protected $timestamps)public $timestamps = false;/** 分數表(ScoreInfo)與課程表(SobjectInfo)、學生信息表(StuInfo)有主外鍵關系* 而且是一對多的關系*/public function StuInfo(){return $this -> belongsTo('StuInfo','s_id');}/** 定義逆向關系指向主鍵表* */public function SobjectInfo(){return $this -> belongsTo('SobjectInfo','soc_id');}
} ?
>
通過以上步驟的處理。表與表之間的一對多關系已確立,以下將介紹在Laravel Administrato 后臺中的實現 下拉列表查詢、綁定等應用
<?phpreturn array('title' => '分數信息', //欄目名'single' => ' >>', //新建描寫敘述'model' => 'ScoreInfo', //分數信息'form_width' => 960, //左邊欄目寬//列表'columns' => array('so_id' => array('title' => '編號','select' => "so_id",'sort_field'=>'so_id'),'s_name'=>array('title'=>'學生姓名','relationship' => 'StuInfo','select' => '(:table).s_name',),'soc_name'=>array('title'=>'課程名稱','relationship' => 'SobjectInfo','select' => '(:table).soc_name',),'score'=>array('title'=>'考試分數','select'=>'score'),),//篩選信息'filters' => array('so_id' => array('title'=>'編號'),'SobjectInfo'=>array('type' => 'relationship','title' => '課程名''name_field' => 'soc_name',),'StuInfo'=>array('type' => 'relationship','title' => '學生姓名','name_field' => 's_name',),'score'=>array('title'=>'考試分數','type' => 'number'),),//改動、新增'edit_fields' => array('StuInfo'=>array('type' => 'relationship','title' => '學生姓名','name_field' => 's_name',),'SobjectInfo'=>array('type' => 'relationship','title' => '課程名','name_field' => 'soc_name',),'score'=>array('title'=>'考試分數','type'=>'text'),));?>
以上演示樣例展示的是 后臺 分數信息 類。 演示樣例中多次使用到 “學生姓名”、“課程名”,盡管他們存儲在不同的表中,但因為我們之前在 Model中已建立了它們之間的 一對多關系,因此我們能夠自由搭配組合
效果圖例如以下:
10個Laravel4開發者必用擴展包:
http://blog.csdn.net/yimiyuangguang/article/details/39756115Laravel Administrator 文檔
http://administrator.frozennode.com/docs/field-type-relationship
Laravel4 中文幫助手冊:
http://pan.baidu.com/s/1jGl6cqa