我有一个会员表 member 但是这张表记录的信息只有登录账号和密码,另外一张表memdesc是存放头像,姓名,等,这时我需要根据member表的mid
和memdesc的mid关联
首先我们在member表下关联memdesc表
public function getMemdesc(){
return $this->hasOne(Memdesc::className(),['mid'=>'mid']); // 这里怎么写,请看文档和结合你的实际表结构,这里是用member的mid去关联memdesc的mid
}
当然到这里不是结束
你首先的去写一个MemberSearch去继承Member表,这个可以用gii生成的就不多说了,不会的话就手动吧
就像这样
namespace backendmodels;
use Yii;
use yiibaseModel;
use yiidataActiveDataProvider;
use commonmodelsMember;
use commonmodelsMemdesc;
class MemberSearch extends Member
{
public $nickname; //这里定义一个属性,就是memdesc表的会员姓名
public function rules()
{
return [
[['mid'], 'integer'],
[['memail', 'musername','nickname'], 'safe'], //这里nickname一定要写,根据你自己的命名去写,不写的话搜索框出不来
];
}
public function scenarios()
{
return Model::scenarios();
}
public function search($params)
{
$query = Member::find();
$query->joinWith(['memdesc']); //加上这句 一看就知道这个就是连表的
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'mid' => $this->mid,
]);
$query->andFilterWhere(['like', 'memail', $this->memail])
->andFilterWhere(['like', 'musername', $this->musername])
->andFilterWhere(['like', 'm_memdesc.nickname', $this->nickname]) ; //这个就是根据nickname参数进行搜索了,注意前面要加表名
return $dataProvider;
}
然后再看Controller代码
public function actionIndex()
{
$searchModel = new MemberSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
接下来就是view了,是不是很开森
use yiihelpersHtml;
use yiigridGridView;
?>
= Html::a(Yii::t('app', 'Create {modelClass}', ['modelClass' => 'Member',]), ['create'], ['class' => 'btn btn-success']) ?>