LoginSignup
5
5

More than 5 years have passed since last update.

Many_to_Many 設定の保存方法

Last updated at Posted at 2012-09-24

FuelPHP 勉強会 東京 Vol.2 で発表した「モデル間のリレーション」http://www.slideshare.net/web2citizen/fuel-phpvol2-14380264 の補足で、Many_to_Many の関係を維持したままの保存方法の例です。
親モデルに紐付ける子モデルの配列を渡して保存してやれば中間テーブルに関係性を保持するデータが保存されます。

<?php
// タグの登録処理
$tags = array();
foreach($tagnames as $tag_name){
    $tag = Model_Tag::find()->where('name', $tag_name)->get_one();
    // 新しいタグの場合はタグテーブルに追加
    if(!$tag){
        $tag = new Model_Tag();
        $tag->name = $tag_name;
        $tag->save();
    }
    array_push($tags, $tag);
}
$skill->tags = $tags;
$skill->save();
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5