码迷,mamicode.com
首页 > 其他好文 > 详细

yii2简述一对一数据表关联

时间:2015-07-13 22:30:37      阅读:186      评论:0      收藏:0      [点我收藏+]

标签: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简述一对一数据表关联

标签:yii2   数据表关联   

原文地址:http://blog.csdn.net/wojiong132/article/details/46867639

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!