首先,好久不见了,最近工作上遇到了许多的问题,换了几家公司,下面进入主题...
我有一个会员表 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 backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Member;
use common\models\Memdesc;
class MemberSearch extends Member
{
public $nickname;<span style="white-space:pre"> </span>//这里定义一个属性,就是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了,是不是很开森
<?php
use yii\helpers\Html;
use yii\grid\GridView;
?>
<div class="news-index">
<?php echo $this->render('_search', ['model' => $searchModel]); ?> //这个先不管它,咱们下回再说这个..
<p>
<?= Html::a(Yii::t('app', 'Create {modelClass}', ['modelClass' => 'Member',]), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'memail',
'musername',
['label'=>'nickname', 'attribute' => 'nickname', 'value' => 'memdesc.nickname' ],//加上这段代码
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
好了,今天就讲这么多了,又要去搬砖了,这些我已经测试过了,已成功,不信?