如何给 ActiveQuery 加上表别名? [ 2.0 版本 ]
新手求助!!!
使用crud后生成,其中class表类关联查询area表
class表类的search函数中
$query = AClass::find();
$query->joinWith("area");
出现了错误,报错为:where字句中,名为id的字段冲突(class表中和area表中都有名为id的字段)
The SQL being executed was: SELECT COUNT(*) FROM `class` LEFT JOIN `area` ON `class`.`areaid` = `area`.`id` WHERE (`id`='1') AND (`areaid`='6')
请问怎么解决这个问题啊?
共 8 个回答
-
chocoboxxf 回答于 2015-06-19 13:27 举报
如果有重名的字段在条件中要带上表名,比如
$query->andWhere([AClass::tableName().'.id' => 1])
暗幻 觉得很赞 -
可以使用 from() 方法覆盖。
$query = Studio::find (); $query->select('s.*,r.name as pname'); $query->from(Studio::tableName() . ' as s'); $query->leftJoin(Region::tableName() . ' as r' , ' r.id = s.province_id');
共 1 条回复 -
$query = Brand::find()->alias('b'); $query = $query->joinWith("createdUser AS c_u", true, 'LEFT JOIN'); $query = $query->joinWith("updatedUser AS u_u", true, 'LEFT JOIN'); $query->andFilterWhere([ 'b.id' => $this->id, 'b.created_at' => $this->created_at, 'b.updated_at' => $this->updated_at, 'b.status' => $this->status, 'b.sort' => $this->sort, 'b.created_by' => $this->created_by, 'b.updated_by' => $this->updated_by, ]);
关联方法
class Brand extends \book\models\Brand { public function getCreatedUser() { return $this->hasOne(User::className(), ['id'=>'created_by']); } public function getUpdatedUser() { return $this->hasOne(User::className(), ['id'=>'updated_by']); } }
共 1 条回复 -
DiscussModel 里面,定义关联表的别名member:
public function getUser() {
return $this->hasOne(MemberModel::class, ['user_code'=>'creator'])->alias('member');
}使用的地方,定义主表的别名discuss
$query = DiscussModel::find()->innerJoinWith('user', true)->alias('discuss');
$discuss = $query->where('parent is null')->orderBy(['hot'=>SORT_DESC])->one();最终执行的代码:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'parent' in 'where clause'\nThe SQL being executed was: SELECTdiscuss
.*,member
.user_code
,member
.nickname
,member
.portrait_url
,member
.gender
FROMtbl_discuss
discuss
INNER JOINtbl_member
member
ONdiscuss
.creator
=member
.user_code
WHERE parent is null ORDER BYhot
DESC从报的错可以看出,别名已经生效了,接下来解决了错误后,只返回了discuss.* 下面的值
换了 延迟加载和即时加载都不出数据,心塞啊,sql打出来也是对的
yanchenghust
最后登录:2015-06-27
在线时长:2小时15分
- 粉丝0
- 金钱0
- 威望0
- 积分20