3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[PHP/symfony1.4]外部キー未設定のテーブルをDoctrineでJOINしたい

Last updated at Posted at 2020-10-28

symfony(1.4)のDoctrineを使って、外部キーが登録されていないテーブル同士をJOINさせるのに躓いた時のメモ。

元のプログラム

$q = StoreTable::getInstance()
      ->createQuery('s')
      ->setHydrationMode(Doctrine_Core::HYDRATE_SCALAR)
      ->select('s.*')
      ->leftJoin('s.StoreItem si')
      ->leftJoin('si.Item i')
      ...()
      ->execute();

StoreItemテーブルには、store_idカラムが存在してるけれど、訳あって外部キーが設定されていない。このテーブルを結合しないと他のテーブルと結合できる方法がない状態だった。

この状態でクエリを実行すると、

Oct 28 12:23:48 symfony [err] {Doctrine_Table_Exception} Unknown relation alias StoreItem

とエラーが出てしまう。

解決策

Doctrineの実行前に、bindを使ってリレーションを一時的に定義する。

修正したプログラム

途方に暮れていたら、無理やり結合させている他の人のコードを見つけた。笑
ドキュメントで見つけられなかったけど下のような書き方をして、リレーションを一時的に?定義できるみたい。

StoreTable::getInstance()
      ->bind(array('StoreItem as StoreItem', array(
        'local'   => 'store_id',
        'foreign' => 'id',
      )),
        Doctrine_Relation::ONE
      );

$q = StoreTable::getInstance()
      ->createQuery('s')
      ->setHydrationMode(Doctrine_Core::HYDRATE_SCALAR)
      ->select('s.*')
      ->leftJoin('s.StoreItem si')
      ->leftJoin('si.Item i')
      ...()
      ->execute();
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?