thinkphp5 关联模型

1一对一关联模型

1-1 实现一对一关联
已知两张表 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');
		  }
		}
1-2 关联查询

         在模板中:this

$user = UserModel::find(1);
	{$user->profile->id};

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

$users = UserModel::with('profile')->select();
 或
 $users = UserModel::hasWhere('profile')->select();
1-3 一对一关联使用where 条件

         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();

2 一对多关联模型

已知三张表 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

2-1实现一对多,一对一 关联
$users = UserModel::with(['cards' => function($query){
                            $query->where(['age' => 18])->with(['cardInfo' =>function($query){
                               $query->field('card_id,name');
                           }]);
                    }])
                   ->where($where)
                  ->select();