SymfonyでマルチプルFKの利用がしたい件(Symfony1.2-Doctrine)
2009年11月26日(木)10:37|天方
こんにちは、天方です。
最近、久しぶりにマルチプルFKが使いたくなりました。(本当は使いたくないのですが…) Symfony1.2のDoctrineでマルチプルFKをしようとしたら、うまくいきませんでした。(注:Propelの場合はaddJoinではできないっぽいです。) 新規で設計するならいいんですが、過去の遺産にアクセスする時には必要なので、なにかしら対応方法があるとうれしいのです。
例えば、下記のように、idとsub_idがあるテーブルをリレーションでつなげる設定を書きたいのです。(実際にはこれはうまく動かなかったです…)
Parent:
columns:
id:
type: integer(4)
notnull: true
sub_id:
type: string(14)
notnull: true
Child:
columns:
id:
type: integer(4)
notnull: true
parent_id:
type: integer(4)
notnull: true
parent_sub_id:
type: string(14)
notnull: true
relations:
Parent:
local: parent_id, parent_sub_id
foreign: id, sub_id
type: one
私の環境だと、
$q = $parent->createQuery(‘p’)
$q->innerJoin(‘p.Child c’);
$q->execute();
と書きたいコードが実行時エラーになります。
とりあえず、下記のような感じでSQLを記述することでで対応しました。
$con = Doctrine_Manager::connection();
$stmt = $con->prepare(‘SELECT
id, sub_id
FROM parent p INNER JOIN child c ON p.id = c.parent_id AND p.sub_id = c.parent_sub_id’);
$stmt->execute(array());
これだとSQLを書かなきゃいけないし、結果がオブジェクトにマッピングされてなくて、他と統一性が失われてしまうので面倒なのですが、いい方法はないだろうか…。