yii2使用小知识(连续补充)

1,打印ar或者query的原始sql:

$query = (new \yii\db\Query())
->select(['a.username','b.item_name'])
->from(['a' => 'user'])
->leftJoin(['b' => 'auth_assignment'], 'a.id = b.user_id')
->where(['a.username' => 'admin'])
->andWhere(['between', 'a.created_at', 1467626063, 1467626064])
->limit(10);

// get the AR raw sql in YII2

$commandQuery = clone $query;

echo $commandQuery->createCommand()->getRawSql();

注意$query不能带all,find() 返回值类型是 yii\db\ActiveQuery, find()->all() 返回的就是数组了。

$users = $query->all();可在同级结构获取多表数据

 

2,class User {

public function getUsergroup()
{
return $this->hasOne(AuthAssignment::className(), ['user_id' => 'id']);
}

}

$model = User::find()->joinWith('usergroup')

->where(['auth_assignment.item_name'=>'超级管理员'])->one();

访问$model ->usergroup->item_name得到关联表数据

->select(['user.username','auth_assignment.item_name'])无法获取item_name,不可在同级结构获取多表数据

 

3,

$a= User::find()
->select(['user.username', 'b.item_name'])
->leftJoin(['b' => 'auth_assignment'], 'user.id = b.user_id')
->andWhere(['user.username' => 'admin'])
->andWhere(['between', 'user.created_at', 1467626063, 1467626064])
->limit(10)->all();

同样的,无法得到item_name的值,但是可以第一次就用andWhere替代where可得到正确结果

posted @ 2016-07-23 16:59  天涯逐梦  阅读(269)  评论(0编辑  收藏  举报