2015-05-13 58 views
4

我試圖在擴展db\activerecord的模型類中使用自定義屬性。Yii2 activerecord自定義屬性

我試過聲明public $categories = [],然後要麼直接通過$model->categories = [1,2,3]分配值,或在我的模型類public function setCategories($ids) {...使用setter方法,然後再通過$model->categories = [1,2,3]分配。

我也試過用$model->setAttribute('categories', [1,2,3])更新屬性。

在所有情況下$model->categories未填充。

我的最終目標是將類別分配到一個模型,然後使用afterSave()beforeSave()

可以這樣做更新數據庫關係/表或我應該db\model延長我的模型類?如果我這樣做,我會失去哪些功能?

編輯 我可能錯誤地報告了我的問題。

我有一個表單,用戶可以選擇特定模型的類別(即「產品」)。所有類別都是預先存在的,並且通過具有一對多關係(一個產品具有多個類別)的聯結表product_category('product_id','category_id')將產品分配給類別。

現在,在處理視圖的控制器中,我收到了一個類別標識列表,我想將它們分配給一個屬性,以便我可以處理它們,即刪除或添加(通過link())product_category表中的條目爲特定產品。

回答

2

它在我看來像你手動試圖做表之間的關係? 爲什麼不使用內置的功能,併爲您照顧?

對於這個(多到多),你需要一個鏈接的ActiveRecord或表格,指示該模型鏈接到我假設這裏的類別(你有一個ActiveRecord被稱爲ModelCategory並具有model_idcategory_id

public function getProductCategories() 
{ 
    return $this->hasMany(ProductCategory::className(), ['product_id' => 'id']); 
} 

public function getCategories() 
{ 
    return $this->hasMany(Category::className(), ['id' => 'category_id']) 
     ->via('productCategories'); 
} 

(您也可以使用viaTable()代替via()和避免額外的方法,那就是你的選擇。)

這意味着,你可以像這樣訪問他們:

$product->categories 

(總是使用神奇的關係函數,它是實際執行數據庫查詢的__get()函數)。

對於分配關係沒有自動方法。 Yii有這個雖然有些輔助功能:

$category = new Category(); 
// Assign attributes 
$category->save(); 

$product = new Product(); 
// Assign attributes 
$product->save(); 

$product->link('categories', $category); 

退房的link-function瞭解更多詳情。 顯然還有其他的方式,但這取決於你的需求。

根據您的額外信息:

public function actionAssignCategories($product, $categories) 
{ 
    $product = Product::findOne($product); 

    $existingCategories = \yii\base\ArrayHelper::getColumn($product->categories, 'category_id'); 
    $removeCategories = array_diff($existingCategories, $categories); 
    $addCategories = array_diff($categories, $existingCategories);    

    foreach ($addCategories as $category) { 
     $category = Category::findOne($category); 
     $product->link('categories', $category); 
    } 

    foreach ($removeCategories as $category) { 
     $category = Category::findOne($category); 
     $product->unlink('categories', $category); 
    } 
} 

未經檢驗的,但應該給你如何解決這一點的想法。

+0

我已經正確地建立了關係,就像您提到的那樣,我可以正確地獲取模型的類別。我現在想要做的是在我的控制器中設置/保存模型的類別。 從我在這裏看到的https://github.com/yiisoft/yii2/issues/2397,我試圖做的應該工作。 – jimmy

2
class ClassName extends \yii\db\ActiveRecord 
{ 

    public $addition; //what attribute you want 

    /* your code */ 

    public function fields() 
    { 
     $fields = parent::fields(); 
     $fields[] = 'addition';  //the value must be the same as the new attribute 

     /* your code */ 

     $this->addition = 'done' 
     return $fields 
    } 
}