1.模型要继承RelationModel,定义关联关系
class MessageModel extends RelationModel{
protected $_link = array(
‘user‘ =>array(
‘mapping_type‘ => self::BELONGS_TO,
‘class_name‘ => ‘User‘,
‘foreign_key‘ => ‘user_id‘,
‘mapping_name‘ => ‘user‘,
),
);
}
2.查询时:用D方法实例化模型,加入relation(true)
public function listAll(){
$message = D(‘message‘);
$list = $message->relation(true)->select();
// dump($list);
if ($list) {
$this->list = $list;
$this->display();
}
}
3.插入时:用D方法实例化模型,模型属性赋值只写外键,加入relation(true)
public function save(){
$message = D(‘message‘);
$message->create();
$message->post_time = date("Y-m-d H:i:s");
$user = session(‘user‘);
$message->user_id = $user[‘id‘]; //这里很关键
$message->status = 1;
// dump($message);
$result = $message->relation(true)->add();
if($result){
$this->success(‘Leave a message success!‘,‘listAll‘,2);
}else{
$this->error(‘Leave a message failed!‘,‘‘,2);
}
}