4
4

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 5 years have passed since last update.

FuelPHPのORMで子モデルを作成する

Posted at

こんな構造をひとつのテーブルで管理したいとする

親: Model_Asset
 子: Model_Asset_Image
  孫: Model_Asset_Image_Jpeg
  孫: Model_Asset_Image_Png
 子: Model_Asset_Text
  孫: Model_Asset_Text_Url
  孫: Model_Asset_Text_Txt

親モデル

fuel/app/classes/asset.php
<?php

class Model_Asset extends \Orm\Model
{
	protected static $_properties = array(
		'id',
		'object_model',
		'object_id',
		'class'=> array( 'default' => 'Model_Asset' ),//ここで子モデルを判別する
		'original_id',
		'priority',
		'filter_name',
		'mime_type',
		'filename',
		'extention',
		'bin',
		'created_at',
		'updated_at',
	);

子モデル

fuel/app/classes/asset/image.php
<?php
use Orm\Model;

class Model_Asset_Image extends Model_Asset
{
	protected static $_properties = array(
		'id',
		'object_model',
		'object_id',
		'class'=> array( 'default' => 'Model_Asset_Image' ),
		'original_id',
		'priority',
		'filter_name',
		'mime_type',
		'filename',
		'extention',
		'bin',
		'created_at',
		'updated_at',
	);
	
	/**
	 * Overrides the query method to allow soft delete items to be filtered out.
	 */
	public static function query($options = array())
	{
		$query = \Orm\Query::forge(get_called_class(), static::connection(), $options);
		
		$query->where( array( 'class' => static::$_properties['class']['default'] ) );

		return $query;
	}

}

孫モデル

  • 同様に好きなだけ作成する

使い方

$img = Model_Asset_Image::find('first');
//select * from assets where class='Model_Asset_Image'; が発行される
$img = Model_Asset_Image_Jpeg::find('first');
//select * from assets where class='Model_Asset_Image_Jpeg'; が発行される
  • has_manyなどでリレーションされていてもよしなにしてくれる
$user = Model_User::find('first',array('related'=>array('img')));
//select * from users inner join assets on users.image_id = assets.id where assets.class = 'Model_Asset_Image_Png'; といった感じ
4
4
1

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?