yii2模型找到关系

时间:2018-02-26 10:01:40

标签: join model-view-controller yii2 relational-database

我有以下查询

    $model_company = Members_companies::find()
            ->select(['members_companies.id', 'companies.name'])
            ->leftJoin('companies', 'members_companies.company = companies.id ')
            ->where(['members_companies.member' => $member])
            ->orderBy(['companies.name' => SORT_ASC])
            ->all();

查询结果显示没有错误。此外,结果还显示了正确的记录。但是没有companies.name列可用结果。 如果我在MYSQL WorkbenchPHPMyAdmin中执行相同的查询,则查询还会显示带有值的companies.name列。

此查询结果相同:

$model_company = Members_companies::find()
        ->select(['members_companies.id', 'companies.name'])
        ->leftJoin('companies', ['members_companies.company' => 'companies.id'])
        ->where(['members_companies.member' => $member])
        ->orderBy(['companies.name' => SORT_ASC])
        ->all();

2 个答案:

答案 0 :(得分:0)

在Members_companies模型中添加新的公共属性$ cname。然后 为companies.name列添加别名,如下所示:

$model_company = Members_companies::find()
        ->select('members_companies.id, companies.name as cname')
        ->leftJoin('companies', ['members_companies.company' => 'companies.id'])
        ->where(['members_companies.member' => $member])
        ->orderBy(['companies.name' => SORT_ASC])
        ->all();

您将看到包含公司名称的cname属性。

答案 1 :(得分:0)

如果你和公司模型有关系,你可以这样写查询

$model_company = Members_companies::find()
        ->select('members_companies.id, companies.name as cname')
        ->joinWith(['companies'])
        ->where(['members_companies.member' => $member])
        ->orderBy(['companies.name' => SORT_ASC])
        ->all();

来源https://forum.yiiframework.com/t/how-to-include-relation-of-relation-in-find-model/84982/2