LoginSignup
8
9

More than 5 years have passed since last update.

FuelPHPでリレーション。JOINを試す。

Last updated at Posted at 2015-09-13

http://qiita.com/ms2sato/items/d678997709e6a388149f
で簡単にFuelPHPを試してみました。

あと大事なことといえば下記らへんでしょうか。

  • routesの変更の仕方
  • リレーションとJOINのやり方。
  • POSTされたデータの癖(これは確認すればOK)

今回はJOIN

どうやら下記の二種類の方法がある様子です。とりあえず先に有効にしていたORMを試すと良さそうだと考えました。

  • Query_Builder_Select
  • ORM

一次情報の翻訳は下記の様子です。これの後半に色々と例が載っています。
http://fuelphp.jp/docs/1.7/packages/orm/crud.html

Modelの作成とMigration

雛形の作成

oil g model comment body:text thread_id:integer

このあたりを見つつ外部キーも入れてみました。編集したマイグレーションのファイルが以下です。

fuel/app/migrations/003_create_comments.php
<?php

namespace Fuel\Migrations;

class Create_comments
{
    public function up()
    {
        \DBUtil::create_table('comments', [
            'id' => ['constraint' => 11, 'type' => 'int', 'auto_increment' => true, 'unsigned' => true],
            'body' => ['type' => 'text'],
            'thread_id' => ['constraint' => 11, 'type' => 'int', 'unsigned' => true],
        ], ['id']);

        \DBUtil::add_foreign_key('comments', [
              'constraint' => 'index_comments_to_thread',
            'key' => 'thread_id',
            'reference' => [
                'table' => 'threads',
                'column' => 'id',
            ],
            'on_delete' => 'CASCADE'
        ]);
    }

    public function down()
    {
        \DBUtil::drop_table('comments');
    }
}

作ったらマイグレーションしてみます。エラー出ずに終了すればOK。

oil refine migrate

エラー出なかったけど思った通り出来なかった時は下記を使って戻します。今回は試しながらやったので何度かdownしたりupしたりを繰り返しました。

oil refine migrate:down

試しにphpMyAdminでデータを作ってみたらちゃんと外部キー制約されたデータが作成できました(thread_idに存在しないthread_idを指定するとエラーでレコードは作成されません)。

モデルのリレーション

リレーションをモデルに記すことで便利なメソッドが使えるようになります。

Thread

thread.php
protected static $_has_many = ['comments'];

Comment

comment.php
protected static $_belongs_to = ['thread'];

リレーションしているデータを取得

http://fuelphp.jp/docs/1.7/packages/orm/crud.html
によると、relatedメソッドを使うと良さそうです。

oil console

して試してみます。

Model_Thread::find('all', ['related' => ['comments']])

先にphpMyAdminで作成したコメントのデータがスレッドと一緒に取れました。バッチリです。

Viewに表示する

先に試した方法で、findにオプションを付ければJOINされるとわかりましたので、下記のように取得部分を編集しました(デフォルトで作られるこの部分のコードってアンチパターンの気がします。if文の中で代入するのはやめるほうがいいと思うのですが)。

thread.php
        if ( ! $data['thread'] = Model_Thread::find($id, ['related' =>['comments']]))

そしてViewを下記のようにすると無事にコメントが表示できました!

thread/view.php
<p>
    <h3>Comments</h3>
    <?php foreach($thread->comments as $index => $comment ) { ?>
        <p><?php echo $comment->body ?></p>
    <?php } ?>
</p>

余談ですが、 <script>alert('test')</script>のようなテキストを入れてもちゃんと画面にサニタイズされているのですね。

今回の対応はこちら
https://github.com/ms2sato/fuelsample/commit/73466f771456ed4dbada09a1bff5ef8aa3a73cdc

8
9
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
8
9