YII2关联示例或via()或viaTable()示例

YII2关联示例或via()或viaTable()示例,yii2,yii2-advanced-app,yii-relations,yii2-rbac,Yii2,Yii2 Advanced App,Yii Relations,Yii2 Rbac,大家好 此示例将帮助您如何使用restful API调用获取客户的产品详细信息,您的API调用应该如下所示: } class Customer extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'customer'; } /** * @inheritdoc */ public function rules() { return

大家好


此示例将帮助您如何使用restful API调用获取客户的产品详细信息,

您的API调用应该如下所示:

}

class Customer extends \yii\db\ActiveRecord
{
/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'customer';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['ID', 'Name'], 'required'],
        [['ID'], 'integer'],
        [['Name'], 'string'],
        [['PhoneNo'], 'string', 'max' => 45]
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'ID' => 'ID',
        'Name' => 'Name',
        'PhoneNo' => 'Phone No',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getOrders()
{
    return $this->hasMany(Order::className(), ['customer_id' => 'ID']);
}

public function getOrderItems()
{
    return $this->hasMany(Orderitem::className(),['Order_id' => 'ID'  ])

            ->via('orders');
        ;
}

public function getProducts()
{
   return  $this->hasMany( Product::className() , ['ID' => 'Product_ID' ] )
           ->via('orderItems') ; 

}

/**
 * @inheritdoc
 * @return CustomerQuery the active query used by this AR class.
 */
public static function find()
{
    return new CustomerQuery(get_called_class());
}

/**
 * @info: call : http://127.0.0.1:8080/api/web/customer?expand=orders for get customer and his orders also;
 * @return type
 */
public function extraFields() 
{
        return ['orders','orderItems','products']; 
}