如何使用联结表Yii2查看数据

时间:2015-03-16 11:17:17

标签: yii2

我有三张桌子

  1. checkoutcounter {id,name}
  2. 用户{id,username}
  3. checkoutcounter_users {id,checkoutcounter_id,user_id}
  4. 我使用gii然后添加 在checkoutcounter模型中(我添加和joinWith和find() - >但它仍然没有工作):

    public function getUser_display()
        {
            return $this->hasMany(User_display::className(), ['id' => 'user_id'])
            ->viaTable(CheckoutcounterUsers::tableName(), ['checkoutcounter_id' => 'id']
            );
        }
    

    在checkoutcounter模型搜索中:

     public function search($params)
        {
            $query = FinanceSettingsCheckoutcounter::find()->with('user_display');
    
            $query->joinWith('user_display');
        }
    

    我应该在checkoutcounter视图中添加什么来获取用户名或用户ID?为什么我在gridview中添加了' =>' user_display.id'它没有显示任何数据?

    echo yii\helpers\Json::encode($dataProvidercheckoutcounter);
    

    显示

    {"query":{"sql":null,"on":null,"joinWith":[[["user_display"],true,"LEFT JOIN"]],"select":null,"selectOption":null,"distinct":null,"from":null,"groupBy":null,"join":null,"having":null,"union":null,"params":[],"where":null,"limit":null,"offset":null,"orderBy":null,"indexBy":null,"modelClass":"app\\models\\FinanceSettingsCheckoutcounter","with":["user_display"],"asArray":null,"multiple":null,"primaryModel":null,"link":null,"via":null,"inverseOf":null},"key":null,"db":null,"id":null}
    

1 个答案:

答案 0 :(得分:0)

我不确定你是如何使用search()函数的,但是你没有使用$ params ..而且它没有返回结果..

我相信查询应该是这样的:

public function search($params)
{
     $result = FinanceSettingsCheckoutcounter::find()->with('user_display')->all();
     echo yii\helpers\Json::encode($result);
}

如果您将此作为搜索模型的一部分使用,则返回dataProvider,请查看此链接

http://www.ramirezcobos.com/2014/04/16/displaying-sorting-and-filtering-model-relations-on-a-gridview-yii2/