Yii2 从多对多相关模型中选择某些字段

Yii2 selecting certain fields from related many to many related model

我管理一个联结 table 来处理 Many to Many 关系。 items 与其 units 之间的关系,其中一项可能有一个或多个单位,一个单位可能有一个或多个单位。

最后,我能够获取某项的所有单位数据,例如:

$item = Items::findOne($id);    
return Json::encode($item->units);

但是,返回的 JSON 对象包含当前操作不需要的字段。我只需要获取单位的 titleid,但它 returns 所有单位字段。

我不知道如何从 Items 模型中的关系设置中调整它。以下是 Items 模型中的关系声明:

public function getItemUnits()
    {
        return $this->hasMany(ItemUnits::className(), ['item_id' => 'id']);
    }

    public function getUnits()
    {
      return $this->hasMany(Units::className(), ['id'=> 'unit_id'])->via('itemUnits');
    }

其中itemUnits为结点模型,item_units table.

您可以加​​入相关的 table 并像这样修改加入查询

Items::find()
->where(['id'=>$id])
->joinWith(['units'=>function($query){
     $query->select(['id','title']);
}])
->one();

我从关系声明中找到了更简单的解决方案。它在 getUnits 方法中。我必须向其中添加 select 方法,如下所示:

public function getUnits()
    {
      return $this->hasMany(Units::className(), ['id'=> 'unit_id'])->select(['id','title'])->via('itemUnits');
}