Answer the question
In order to leave comments, you need to log in
How to link and access related tables in Yii2?
Good morning. Something I can’t understand in any way how to work with related tables, there are 3 tables:
public function getSocialUsers()
{
return $this->hasMany(SocialUsers::className(), ['social_id' => 'id_social']);
}
public function getSocialUsers()
{
return $this->hasMany(SocialUsers::className(), ['user_id' => 'id_user']);
}
public function getUser()
{
return $this->hasMany(User::className(), ['id_user' => 'user_id']);
}
public function getSocial()
{
return $this->hasMany(Social::className(), ['id_social' => 'social_id']);
}
public function actionIndex()
{
$id = Yii::$app->user->identity['id_user'];
$profile = Profile::find()->where(['user_id' => $id])->asArray()->one();
$socials = SocialUsers::find()->asArray()->all();
return $this->render('index', [
'profile' => $profile,
'socials' => $socials,
]);
}
<?php if(isset($socials)):?>
<div class="list-group">
<?php foreach ($socials as $social):?>
<a href="#" class="list-group-item"><i class="fa fa-facebook"></i> </a>
<?php endforeach;?>
</div>
<?php endif;?>
Answer the question
In order to leave comments, you need to log in
class Social extends ActiveRecord {
public function getPivotSocialUser(){
return $this->hasMany(SocialUser::class, ['social_id' => 'id');
}
public function getUsers(){
return $this->hasMany(User::class, ['id' => 'user_id')->via('pivotSocialUser');
}
}
class User extends ActiveRecord {
public function getPivotSocialUser(){
return $this->hasMany(SocialUser::class, ['user_id' => 'id');
}
public function getSocials(){
return $this->hasMany(Social::class, ['id' => 'social_id')->via('pivotSocialUser');
}
}
$social = Social::findOne(['name' => 'facebook']);
var_dump($social->users); // все пользователи фейсбука
$user = User::findOne(['name' => 'admin']);
var_dump($user->socials); // все социальные сети админа
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question