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

时间:2019-10-18 18:53:59

标签: php mysql yii2

我是yii2的新手。我有CONDITIONALLY 2个表:用户(id,地址,...)和个人资料(id,user_id,...)。

我想得到这样一个计划的数组:

  {
        "ID": 2,
        "User_ID": 6,
        "Address":???
},
  {
        "ID": 3,
        "User_ID": 11,
        "Address":??
}
]

为此,我在控制器中调用Profiles :: getProfiles(condition);

public static function getProfiles(condition){
   return self::find->where(condition)->all();

现在我有一个ActiveRecords对象数组,但是没有address属性。如果将address属性添加到它们,则会收到错误消息设置未知属性:app \ models \ Profiles :: Address

我读到有关hasMany,hasOne的信息,但我需要将address属性与其他个人资料数据相提并论。

请告诉我正确的做法

2 个答案:

答案 0 :(得分:0)

在个人资料类中:

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();

答案 1 :(得分:0)

不要这么复杂。在yii2中非常简单,请看:

修改您的个人资料模型

1-验证规则:

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

2- getUser():

public function getUser() {
    return $this->hasOne(User::className(), ['id' => 'user_id']);
}

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

$address = Profile::findOne($id)->user->address;
相关问题