yii2简述一对一数据表关联

1、建两个表publish:pub_id 和 images:pub_id,image_path;
2、使用gii的crud生成代码
3、在models内Publish.php内写关联函数

public function getImage() {
        return $this->hasOne(Images::className(),['pub_id'=>'pub_id']);
    }

4、在models内publishSearch.php内写joinWith()函数

    public function search($params) {
        $query = IhpTPublishInfo::find();
        $query->joinWith(['image']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {

            return $dataProvider;
        }

        $query->andFilterWhere([
            'pub_id' => $this->pub_id,

        ]);

        return $dataProvider;
    }
}

5、在view内index.php的gradview中调用,$model->image->img_path,其中image对应getImage()函数

    <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'pub_id', ['label'=>'缩略图','format'=>'raw','value'=>function($m){ //var_dump($m->image); if(is_object($m->image)){ return Html::img($m->image->img_path,['alt' => '缩略图','width' => 80]); } }], ['class' => 'yii\grid\ActionColumn'], ['label'=>'添加','format'=>'raw','value'=>function($data){ $url="http://"; return Html::a('添加推荐', $url, ['class' => 'btn btn-success']); }], ], ]); ?>

你可能感兴趣的:(yii2,数据表关联)