简体   繁体   English

Yii2 activerecord从相关表中选择自定义属性

[英]Yii2 activerecord select custom attributes from related table

When I'm trying to select custom attributes from record 当我尝试从记录中选择自定义属性时

 $data = Emotion::find()
        ->select('em_id, em_name, tbl_post.post_id, tbl_post.post_header')
        ->where(['em_id' => $id])
        ->joinWith('posts')
        ->one();

I've got an answer model, where related field have full set of table fields. 我有一个答案模型,其中相关字段具有完整的表字段集。 Trace message looks like this: 跟踪消息如下所示:

 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'...

So, maybe i did something wrong or this is a framework issue. 因此,也许我做错了什么,或者这是一个框架问题。

Found a workaround here: Yii2 GitHub issue 在此处找到解决方法: Yii2 GitHub问题

Which for my case looks like this: 对于我的情况,看起来像这样:

$data = Emotion::find()
        ->select('em_id, em_name, tbl_post.post_id, tbl_post.post_header')
        ->where(['em_id' => $id])
        ->joinWith('posts')
        ->createCommand()
        ->queryAll();

And the output of this request will be an raw array. 该请求的输出将是原始数组。 Is there an another way to have an ActiveRecord object in a response data? 还有另一种方法可以在响应数据中包含ActiveRecord对象吗?

You should simply modify the relation query, eg : 您应该简单地修改关系查询,例如:

$data = Emotion::find()
    ->select('em_id, em_name')
    ->where(['em_id' => $id])
    ->with([
        'posts' => function($query) {
            $query->select('post_id, post_header');
        }
    ])->one();

And you don't need joinWith since you don't use posts in the main query. 而且您不需要joinWith因为您不会在主查询中使用帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM