已知兩張表 user(用戶表) 和 profile(用戶簡介表) 是一一對應的 user: id profile: id user_id age name
在 user 模型中實現關聯:app
use app\common\model\ProfileModel; class UserModel extends Model{ public function profile(){ return $this->hasOne('ProfileModel','user_id','id'); } }
在模板中:this
$user = UserModel::find(1); {$user->profile->id};
在控制器中: with() 或 hasWhere()code
$users = UserModel::with('profile')->select(); 或 $users = UserModel::hasWhere('profile')->select();
1-3-1 with( )ci
$users = UserModel::with(['profile' => function($query){ $query->where(['age' => 18])->filed('age,id,user_id'); # user_id 必要字段 }]) ->where(['id' => 2]) ->find();
1-3-2 hasWhere( )it
$user = UserModel::hasWhere('profile',['age'=>'18'])->find();
已知三張表 user表關聯card表(一對多),card表關聯card_info表(一對一) user id card id user_id age card_info id card_id
userModel 模型:io
class UserModel extends Model(){ public function cards(){ return $this->hasMany('CardModel','user_id','id'); } }
card 模型: class CardModel extends Model(){ public funcion cardInfo(){ reuturn $this->hasOne('cardInfoModel','card_id','id'); } }function
$users = UserModel::with(['cards' => function($query){ $query->where(['age' => 18])->with(['cardInfo' =>function($query){ $query->field('card_id,name'); }]); }]) ->where($where) ->select();