think php5关联模型,thinkphp5 关联模型

1一对一关联模型

1-1 实现一对一关联

已知两张表 user(用户表) 和 profile(用户简介表) 是一一对应的

user:

id

profile:

id

user_id

age

name

在 user 模型中实现关联:

use app\common\model\ProfileModel;

class UserModel extends Model{

public function profile(){

return $this->hasOne('ProfileModel','user_id','id');

}

}

1-2 关联查询

在模板中:

$user = UserModel::find(1);

{$user->profile->id};

在控制器中: with() 或 hasWhere()

$users = UserModel::with('profile')->select();

$users = UserModel::hasWhere('profile')->select();

1-3 一对一关联使用where 条件

1-3-1 with( )

$users = UserModel::with(['profile' => function($query){

$query->where(['age' => 18])->filed('age,id,user_id'); # user_id 必要字段 不要加select() 方法

}])

->where(['id' => 2])

->find();

1-3-2 hasWhere( )

$user = UserModel::hasWhere('profile',['age'=>'18'])->find();

2 一对多关联模型

已知三张表 user表关联card表(一对多),card表关联card_info表(一对一)

user

id

card

id

user_id

age

card_info

id

card_id

userModel 模型:

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'); } }

2-1实现一对多,一对一 关联

$users = UserModel::with(['cards' => function($query){

$query->where(['age' => 18])->with(['cardInfo' =>function($query){

$query->field('card_id,name');

}]);

}])

->where($where)

->select();

你可能感兴趣的:(think,php5关联模型)