Yii ActiveRecord 的via和viaTable示例

Yii中,將兩個不相關的表利用中間表關聯有via和viaTable兩種方法,這裏經過用戶權限查詢來進行示例。php

    

關係如上,須要創建三個表 用戶表 權限表web

用戶表數組

數據:app

權限表yii

數據:ui

關聯表this

數據:spa

而後建立權力模型blog

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Power extends ActiveRecord
{
    public static function tableName()
    {
        return 'power';
    }
}

用戶模型get

<?php

namespace app\models;

use yii\db\ActiveRecord;
use app\models\Power;

class Users extends ActiveRecord
{
    public static function tableName()
    {
        return 'users';
    }

    public function getPower()
    {
        return $this -> hasMany(Power::class, ['id' => 'power_id']) -> viaTable('users-power', ['user_id' => 'user_id']);
    }
}

關聯模型:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class UserPower extends ActiveRecord
{
    public static function tableName()
    {
        return 'users-power';
    }
}

控制器代碼

<?php

namespace app\controllers;

use yii\web\Controller;
use app\models\Users;
use app\models\Power;

class UserController extends Controller
{
    public function actionIndex()
    {
        //查詢user_id爲6的用戶權限  
        $user = Users::findOne(['user_id' => 6]);
        print_r( $user -> getPower() -> asArray() -> all());
    }
}

運行結果:

 其中用戶模型中經過viaTable來經過關聯表查詢

$this -> hasMany(Power::class, ['id' => 'power_id']) -> viaTable('users-power', ['user_id' => 'user_id']);

各個數組字段參數含義,hasMany第二個數組中,鍵名爲前面的Power::class對應的模型id字段,值爲關聯表中前面Power::class的id對應的字段,即power表中的id對應關聯表中的power_id, viaTable第二個參數數組,鍵名爲關聯表中的字段,值爲當前primaryModel對應的字段,即關聯表中的user_id對應當前user表中的user_id。

via方法

via參數爲AR類中定義的關聯名,修改用戶模型:

<?php

namespace app\models;

use yii\db\ActiveRecord;
use app\models\Power;
use app\models\UserPower;

class Users extends ActiveRecord
{
    public static function tableName()
    {
        return 'users';
    }
    //經過getUserPower來進行操做
    public function getUserPower()
    {
        return $this -> hasMany(UserPower::class, ['user_id' => 'user_id']);
    }


    public function getPower($uid = 6)
    {
        return $this -> hasMany(Power::class, ['id' => 'power_id']) -> via('userPower');
    }
}

運行:

相關文章
相關標籤/搜索