简体   繁体   English

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

[英]How to display data from two different tables in yii2?

I am new to yii2.我是 yii2 的新手。 I have CONDITIONALLY 2 tables: Users (id, address, ...) and Profiles (id, user_id, ...).我有 CONDITIONALLY 2 个表:用户(id,地址,...)和配置文件(id,user_id,...)。

I want to get an array of such a plan:我想得到这样一个计划的数组:

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

To do this, I call in the controller Profiles::getProfiles(condition);为此,我调用 controller Profiles::getProfiles(condition);

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

Now I have an array of ActiveRecords objects, but without an address property.现在我有一个 ActiveRecords 对象数组,但没有地址属性。 If I add the address property to them, I get an error Setting unknown property: app\models\Profiles::Address如果我将地址属性添加到它们,我会收到错误设置未知属性:app\models\Profiles::Address

I read about hasMany, hasOne, but I need the address property to be on par with the rest of the profile data.我阅读了有关 hasMany、hasOne 的信息,但我需要将地址属性与配置文件数据的 rest 相提并论。

Please tell me how to do it right请告诉我如何正确地做

In Profile class:在配置文件 class 中:

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’]);
}

Then you can do the following from wherever you want:然后,您可以从任何地方执行以下操作:

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

Don't make it this complicated.不要把事情弄得这么复杂。 it's very easy in yii2, look:在 yii2 中很容易,看:

Modify your Profile Model :修改您的个人资料 Model

1 - validation rules: 1 - 验证规则:

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

2- getUser(): 2- 获取用户():

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

from now on, every instance of profile model, will have an attribute named ->user (look at the name of the method: get User () ), and it is a active record object of the User model .从现在开始,配置文件 model 的每个实例,都会有一个名为->user的属性(查看方法名称:get User ()),它是用户 Z20F35E630DAF44DBFA4C3F68F53的活动记录 object See, we can access address everywhere just like this:看,我们可以像这样在任何地方访问地址:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM