当我试图从记录中选择自定义属性时
$data = Emotion::find()
->select('em_id, em_name, tbl_post.post_id, tbl_post.post_header')
->where(['em_id' => $id])
->joinWith('posts')
->one();
我有一个答案模型,其中相关字段有一组完整的表字段。跟踪消息如下:
app'models'Emotion#1
( [yii'db'BaseActiveRecord:_attributes] =>
[ 'em_id' => 4
'em_name' => 'test_em']
[yii'db'BaseActiveRecord:_related] =>
[ 'posts' =>
[ 0 => app'models'Post#2 ( [yii'db'BaseActiveRecord:_attributes] =>
[ 'post_id' => 10
'post_header' => 'some header'
'post_date' => '2015-06-24 13:40:25',
'post_descr' => 'Rocco, continue the joke'
'post_content' => 'test content'...
所以,也许我做错了什么,或者这是一个框架问题。
在这里找到了一个解决方法:Yii2 GitHub问题
在我的案例中,看起来是这样的:
$data = Emotion::find()
->select('em_id, em_name, tbl_post.post_id, tbl_post.post_header')
->where(['em_id' => $id])
->joinWith('posts')
->createCommand()
->queryAll();
这个请求的输出将是一个原始数组。有没有其他方法可以在响应数据中包含ActiveRecord对象?
您应该简单地修改关系查询,例如:
$data = Emotion::find()
->select('em_id, em_name')
->where(['em_id' => $id])
->with([
'posts' => function($query) {
$query->select('post_id, post_header');
}
])->one();
并且您不需要joinWith
,因为您在主查询中不使用posts。