zkh90644 2015-06-05 16:13:21 5555次浏览 2条回复 1 0 0

首先先感谢前辈http://www.yiichina.com/tutorial/120 的教程有点了解,但是使用中还是出现了问题。请各位大神解决。谢谢

我的表为 gb_user(id,username),gb_leaveword(id,userid) Leaveword.php中通过gii生成了以下代码

class Leaveword extends \app\core\base\BaseActiveRecord
{
    ***
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'userid']);
    }
}

LeavewordSearch.php中加入了以下代码

class LeavewordSearch extends Leaveword
{
    public $username; //<=====就是加在这里
    ***
}

修改了LeavewordSearch中的search函数

public function search($params)
    {
        $query = Leaveword::find();
		$query->join(['user']);   //添加了这个
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $dataProvider->setSort([
        		'attributes' => [
        		/* 其它字段不要动 */
        		/*  下面这段是加入的 */
        		/*=============*/
        		'username' => [
        		'asc' => ['gb_user.username' => SORT_ASC],
        		'desc' => ['gb_user.username' => SORT_DESC],
        		'label' => 'UserName'
        		],
        		/*=============*/
        	]
        ]);
        
        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'userid' => $this->userid,
            'createtime' => $this->createtime,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'content', $this->content]);
        $query->andFilterWhere(['like', 'gb_user.username', $this->username]);//加入了这段

        return $dataProvider;
    }

最后修改了Leaveword的index.php文件

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],		//添加最后的序号。

            'id',
			['label'=>'用户',  'attribute' => 'username',  'value' => 'gb_user.username' ],
            'createtime',
            'title',
            'content:ntext',
            ['class' => 'yii\grid\ActionColumn'],//这一行是最后增加操作方法的。
        ],
    ]); ?>

最后出现的问题是:Getting unknown property: app\models\Leaveword::gb_user,无法找到gb_user对象,请问有什么方法解决呢?

  • 回复于 2015-06-05 16:32 举报

    问题解决了修改了最后的

    ['label'=>'用户',  'attribute' => 'username',  'value' => 'gb_user.username' ],
    =>
    ['label'=>'用户',  'attribute' => 'username',  'value' => 'user.username' ],
    ```
    
    , , 觉得很赞
  • 回复于 2016-08-04 16:53 举报

    表连接$query->join(['user']); //添加了这个

    不用添加关联字段 ON 能行吗

您需要登录后才可以回复。登录 | 立即注册