CRUD: 作成、読み取り、更新、削除
一度あなたのモデルを設定したそれは、作成、読み取り、更新、
およびデータベース内のエントリを行います。
作成
// オプション 1
$new = new Model_Example();
$new->property = 'something';
$new->save();
// オプション 2, forge メソッドでインスタンスを作成して使用する。
$new = Model_Example::forge();
$new->property = 'something';
$new->save();
save() した後、 model がデータベースに保存されていて、
主キーに auto_increment を使用している場合は、保存後に自動的にインスタンスに設定されます。
配列からモデルのプロパティを設定することができます:
$props = array('property' => 'something');
// "new" を使用する。
$new = new Model_Example($props);
$new->save();
// オプション 2, forge メソッドでインスタンスを作成して使用する。
$new = Model_Example::forge($props);
$new->save();
読み取り
Or actually find(). The find method can be used in 3 ways: find a specific id (primary
key), find first/last or all entries with conditions, or use method chaining to fetch. All possible
selection methods (where, or_where, order_by, etc) can be found at the bottom of the page.
IDから検索する
// ID=2の記事を検索する
$entry = Model_Article::find(2);
// 複合主キーを使用している場合
$entry = Model_Article::find(array(2, 'foo'));
この例では、ID が見つからなかったときは Model_Article インスタンスまたは null を返します。
最初と最後を検索する
// 最初のエントリーを検索する
$entry = Model_Article::find('first');
// date カラムで並び替えて最新のエントリーを検索する
$entry = Model_Article::find('last', array('order_by' => 'date'));
この例では、ID が見つからなかったときは Model_Article のインスタンスまたはnullを返します。
すべてを検索する
// すべての記事を検索する。
$entry = Model_Article::find('all');
// category_id カラムの値が 1 の記事を検索し、 date カラムを降順に並び替える。
$entry = Model_Article::find('all', array(
'where' => array(
array('category_id', 1),
),
'order_by' => array('date' => 'desc'),
));
// category_id カラムの値が 1 か 2 の記事を検索する。
$entry = Model_Article::find('all', array(
'where' => array(
array('category_id', 1),
'or' => array(
array('category_id', 2),
),
),
));
この例では、それは常に Model_Article のインスタンスの配列を返します。
メソッドチェーンを使用して見つける
When you use the find() method without properties, it will be considered to be an
error situation. Currently it will return an Orm\Query object which you can use, and possibly
reuse to find entries. This behaviour might change in the future, so using this is discouraged,
use the query() method instead.
$query = Model_Article::query()->where('category_id', 1)->order_by('date', 'desc');
// ページネーションのための記事の総数を知りたい場合。
$number_of_articles = $query->count();
// 最大の ID の値を知りたい場合。
$number_of_articles = $query->max('id');
// 一番最初に投稿された記事の日付を知りたい場合。
$number_of_articles = $query->min('date');
// 1 件だけ取得した場合。
$newest_article = $query->get_one();
// 以前のクエリに取得したい件数の制限を加えて、複数の記事を取得する場合。
$all_articles = $query->limit(15)->get();
All these methods are equally valid, the four other methods of find actually use the Query object as
well but don't return it.
Partial column selects
By default all ORM find methods will select all table columns. You can use the select array
entry or the select() method to alter this behavior.
// using the array method. select only the 'name' and 'date' columns
$entry = Model_Article::find('last', array('select' => array('name', 'date')));
// same, but then using the chaining method
$entry = Model_Article::query()->select('name', 'date')->get();
// using the array method. select all columns except the 'date' column
$entry = Model_Article::find('all', array('select' => array(array('date' => false))));
// same, but then using the chaining method
$entry = Model_Article::query()->select(array('date' => false))->get();
更新
$entry = Model_Article::find(4);
$entry->title = 'My first edit';
$entry->author = 'Total n00b';
$entry->save();
That's it, nothing more to it: Find, change properties and save.
You can also set properties on the model from an array:
$entry = Model_Article::find(4);
$entry->set(array(
'title' => 'My first edit',
'author' => 'Total n00b'
));
$entry->save();
削除
$entry = Model_Article::find(4);
$entry->delete();
Again nothing more to it: Find and delete.
In the previous example the $entry variable and its object still exist. The
primary keys are however set to null and the object itself is considered a new instance. If
you save it after deletion it will be re-entered into the database and be given a new primary key when
auto_increment is switched on.
All selection methods when using find
select |
string $column, [string $more_columns,] | array $filter |
// Find only some columns
Model_Article::query()->select('id', 'name');
Model_Article::find('all', array('select' => array('id', 'name')));
// Find all columns except 'name'
Model_Article::query()->select(array('name' => false));
Model_Article::find('all', array('select' => array(array('name' => false))));
|
related |
string|array $relation, [array $conditions] |
// include related models in the find
Model_Article::query()->related(array('author', 'comments'));
Model_Article::find('all', array('related' => array('author', 'comments')));
// include conditions on the relation (only supported when chaining)
Model_Article::query()
->related('author', array('where' => array(array('active', '=', 1))));
// include multiple conditions on the relation
Model_Article::query()
->related('author', array('where' => array(array('active', '=', 1), array('status', '=', 'X'))));
|
use_view |
string $viewname |
// use a view to retrieve data
Model_Article::query()->use_view('with_comments');
Model_Article::find('all', array('use_view' => 'with_comments'));
|
where |
string $column, [string $operator,] mixed $value |
// Single where
Model_Article::query()->where('id', 4);
Model_Article::find('all', array('where' => array('category_id' => 5)));
// Multiple where usage examples
Model_Article::query()->where('id', 4)->where('category_id', '>', 1);
Model_Article::query()->where(array('id' => 4, 'category_id' => 6));
Model_Article::find('all', array('where' => array(array('category_id', '=', 5), array('publish', '<', time()))));
// Using or where
Model_Article::query()->where('id', 4)->or_where('id', 5);
|
order_by |
string $column, [string $direction] |
// Single order_by
Model_Article::query()->order_by('name', 'desc');
Model_Article::find('all', array('order_by' => array('name' => 'desc')));
// Multiple order_by usage examples
Model_Article::query()->order_by('name', 'desc')->order_by('category_id', 'asc');
Model_Article::query()->order_by(array('name' => 'desc', 'category_id' => 'asc'));
Model_Article::find('all', array('order_by' => array(array('name' => 'desc', 'category_id' => 'asc'))));
|
limit |
int $limit |
// limit with relation consistence
Model_Article::query()->limit(10);
Model_Article::find('all', array('limit' => 10));
|
rows_limit |
int $limit |
// limit without relation consistence
Model_Article::query()->rows_limit(10);
Model_Article::find('all', array('rows_limit' => 10));
|
offset |
int $offset |
// offset with relation consistence
Model_Article::query()->offset(10);
Model_Article::find('all', array('offset' => 10));
|
rows_offset |
int $offset |
// offset without relation consistence
Model_Article::query()->rows_offset(10);
Model_Article::find('all', array('rows_offset' => 10));
|
Do not mix the two! A combination of limit and rows_offset (or the other way around) will
lead to unexpected results!
In this context, relation consistence means that by default when you query including related models,
the ORM will make sure the related results are consistent. This means that your results aren't always exactly
limited. For example, if the first parent in the result has 12 children, your resultset will contain 12 records
even if you have used limit(10). When you use rows_limit(10), the resultset will only contain
10 records, but 2 related records will be missing, and can not be retrieved later because the results will be cached
and the cache handler doesn't know the results were incomplete!
Complex where clauses
Using chaining you can create more complex where clauses, using and, or and nesting
// complex where clause
Model_Article::query()
->where('author', '=', 16)
->and_where_open()
->where('date', '<', time())
->or_where('draft', '=', 1)
->and_where_close();
// creates WHERE `author` = 16 AND (`date` < 1348404127 OR `draft` = 1)
To create a nested OR, use or_where_open() and or_where_close(). Allways make sure
your open and close methods match!
Subqueries can be created by constructing a seperate query object and using get_query() to parse it.
$subQuery = Model_Article::query()
->select('author')
->where('date', '<', time())
->where('draft', '=', 1);
Model_Article::query()
->where('author', '=', 16)
->or_where('author', $subQuery->get_query(true))
->get();
It is also possible to perform custom SQL statements and have the result returned as an Orm model (or list of models). Although this is not part of the Orm itself it is useful to know. Take a look at the DB::query() function for more information.
DB::query('SELECT * FROM `articles` WHERE `id` = 1')->as_object('Model_Article')->execute();
It is recommended that you use the query() function where ever possible though