Php 如何在yii2中显示来自两个不同表的数据?

Php 如何在yii2中显示来自两个不同表的数据?,php,mysql,yii2,Php,Mysql,Yii2,我是yii2的新手。我有两个有条件的表:用户(id,地址,…)和配置文件(id,用户id,…) 我想得到一系列这样的计划: { "ID": 2, "User_ID": 6, "Address":??? }, { "ID": 3, "User_ID": 11, "Address":?? } ] 为此,我调用controllerprofiles::getProfiles(条件) 现在我有了一个A

我是yii2的新手。我有两个有条件的表:用户(id,地址,…)和配置文件(id,用户id,…)

我想得到一系列这样的计划:

  {
        "ID": 2,
        "User_ID": 6,
        "Address":???
},
  {
        "ID": 3,
        "User_ID": 11,
        "Address":??
}
]
为此,我调用controllerprofiles::getProfiles(条件)

现在我有了一个ActiveRecords对象数组,但没有address属性。如果我将address属性添加到它们中,则会出现一个错误设置unknown property:app\models\Profiles::address

我读过HasMulk,HasOne,但是我需要地址属性与其他配置文件数据保持一致。< /P> 请告诉我如何在Profile类中正确操作:

use app\models\User;

//within the body of the Profile class itself
public $address;
public function getUser(){
    return $this->hasOne(User::class,[‘id’=>’User_ID’]);
}
然后,您可以在任意位置执行以下操作:

$result = Profile::find()
    ->joinWith(‘user’)
    ->select([
     ‘profile.id’, // assumes the table name is profile
    ‘user.address’, // assumes the table name is user
    ])
->where([‘profile.id’=>$value])
->all();
在配置文件类中:

use app\models\User;

//within the body of the Profile class itself
public $address;
public function getUser(){
    return $this->hasOne(User::class,[‘id’=>’User_ID’]);
}
然后,您可以在任意位置执行以下操作:

$result = Profile::find()
    ->joinWith(‘user’)
    ->select([
     ‘profile.id’, // assumes the table name is profile
    ‘user.address’, // assumes the table name is user
    ])
->where([‘profile.id’=>$value])
->all();

别把事情弄得这么复杂。yii2非常简单,看:

修改您的配置文件模型

1-验证规则:

public function rules() {
    return [
        [['user_id'], 'exist', 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
    ];
}
2-getUser():

从现在起,配置文件模型的每个实例都将有一个名为
->user
(查看方法名称:getuser())的属性,它是用户模型的活动记录对象。 看,我们可以在任何地方访问地址,就像这样:

$address = Profile::findOne($id)->user->address;

别把事情弄得这么复杂。yii2非常简单,看:

修改您的配置文件模型

1-验证规则:

public function rules() {
    return [
        [['user_id'], 'exist', 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
    ];
}
2-getUser():

从现在起,配置文件模型的每个实例都将有一个名为
->user
(查看方法名称:getuser())的属性,它是用户模型的活动记录对象。 看,我们可以在任何地方访问地址,就像这样:

$address = Profile::findOne($id)->user->address;

这对我不起作用。仅从配置文件表返回列。我认为它发生了,因为配置文件的模型并没有属性地址。你还有其他想法吗?如果查询没有失败,那么它一定成功了。如果找不到连接,它将完全失败。配置文件没有地址,但我们已将配置文件加入到用户,其中添加了。如果您将模型
用户
添加到
配置文件
中,则必须以
$Profile->user->address
的形式访问地址。这是因为
ActiveQuery
将只使用它自己的属性填充
Profile
模型。如果您想直接访问它,您需要将
public$address
属性添加到
Profile
中,或者在查询中使用
asArray()
。它对我不起作用。仅从配置文件表返回列。我认为它发生了,因为配置文件的模型并没有属性地址。你还有其他想法吗?如果查询没有失败,那么它一定成功了。如果找不到连接,它将完全失败。配置文件没有地址,但我们已将配置文件加入到用户,其中添加了。如果您将模型
用户
添加到
配置文件
中,则必须以
$Profile->user->address
的形式访问地址。这是因为
ActiveQuery
将只使用它自己的属性填充
Profile
模型。如果要直接访问,您需要将
public$address
属性添加到
Profile
中,或者在查询中使用
asArray()