PHPackages                             windwalker/datamapper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. windwalker/datamapper

ActiveWindwalker-package[Framework](/categories/framework)

windwalker/datamapper
=====================

Windwalker DataMapper package

3.5.23(5y ago)24.1k12LGPL-2.0-or-laterPHPPHP &gt;=7.1.3

Since Apr 12Pushed 5y ago3 watchersCompare

[ Source](https://github.com/ventoviro/windwalker-datamapper)[ Packagist](https://packagist.org/packages/windwalker/datamapper)[ Docs](https://github.com/ventoviro/windwalker-datamapper)[ RSS](/packages/windwalker-datamapper/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (5)Versions (86)Used By (2)

Windwalker DataMapper
=====================

[](#windwalker-datamapper)

Installation via Composer
-------------------------

[](#installation-via-composer)

Add this to the require block in your `composer.json`.

```
{
    "require": {
        "windwalker/datamapper": "~3.0"
    }
}
```

Getting Started
---------------

[](#getting-started)

### Prepare Windwalker Database object

[](#prepare-windwalker-database-object)

```
use Windwalker\Database\DatabaseFactory;

// Make the database driver.
$db = DatabaseFactory::getDbo(
    'mysql',
	array(
		'driver'   => 'mysql',
		'host'     => 'localhost',
		'user'     => 'root',
		'password' => 'xxxx',
		'database' => 'mydb',
		'prefix'   => 'prefix_'
	)
);
```

The DatabaseDriver will be cached in Factory, now DataMapper will auto load database driver.

See [Database](https://github.com/ventoviro/windwalker-database#windwalker-database)

Create DataMapper
-----------------

[](#create-datamapper)

```
use Windwalker\DataMapper\DataMapper;

$fooMapper = new DataMapper('#__foo');

$fooSet = $fooMapper->find(array('id' => 1));
```

Inject DB to DataMapper

```
// $db is Windwalker DatabaseDriver
$mapper = new DataMapper('table', null, $db);
```

Custom primary keys:

```
// If keep keys NULL, the default `id` will auto set.
$mapper = new DataMapper('table'); // Keys: array('id')

// Set custom key
$mapper = new DataMapper('table', 'table_id'); // Keys: array('table_id')

// Set multiple keys
$mapper = new DataMapper('table', array('table_id', 'uuid')); // Keys: array('table_id', 'uuid')
```

### Extend It

[](#extend-it)

You can also create a class to operate specific table:

```
class FooMapper extends DataMapper
{
    protected static $table = '#__foo';

    protected static $keys = 'id';
}

$data = (new FooMapper)->findAll();
```

Or using facade:

```
use Windwalker\DataMapper\AbstractDatabaseMapperProxy;

abstract class FooMapper extends AbstractDatabaseMapperProxy
{
    protected $table = '#__foo';

    protected $keys = 'id'; // Keep NULL will use default `id`
}

$data = FooMapper::findOne(array('id' => 5, 'alias' => 'bar'));
```

Find Records
------------

[](#find-records)

Find method will fetch rows from table, and return `DataSet` class.

### find()

[](#find)

Get id = 1 record

```
$fooSet = $fooMapper->find(array('id' => 1));
```

Fetch published = 1, and sort by `date`

```
$fooSet = $fooMapper->find(array('published' => 1), 'date');
```

Fetch published = 1, language = en-US, sort by `date` DESC and start with `30`, limit `10`.

```
$fooSet = $fooMapper->find(array('published' => 1, 'language' => 'en-US'), 'date DESC', 30, 10);
```

Using array, will be `IN` condition:

```
$fooSet = $fooMapper->find(array('id' => array(1,2,3))); // WHERE id IN (1,2,3)
```

### findOne()

[](#findone)

Just return one row.

```
$foo = $dooMapper->findOne(array('published' => 1), 'date');
```

### findAll()

[](#findall)

Equal to `find(array(), $order, $start, $limit)`.

### Find With Custom Query

[](#find-with-custom-query)

```
$fooMapper = new DataMapper('#__foo');

$fooMapper->where('a = "b"') // Simple where
	->where('%n = $q', 'foo', 'bar') // Where format
	->where('flower = :sakura')->bind('sakura', 'Sakura') // Bind params
	->orWhere(array('c = d', 'e = f')) // AND (c=d OR e=f)
	->having('...')
	->limit(10, 20) // Limit, offset
	->order('created DESC') // Can be array or string
	->select(array('id', 'title', 'alias')) // Can be array or string
	->find();
```

The available query methods.

- `join($type = 'LEFT', $alias, $table, $condition = null, $prefix = null)`
- `leftJoin($alias, $table, $condition = null, $prefix = null)`
- `rightJoin($alias, $table, $condition = null, $prefix = null)`
- `nnerJoin($alias, $table, $condition = null, $prefix = null)`
- `outerJoin($alias, $table, $condition = null, $prefix = null)`
- `call($columns)`
- `group($columns)`
- `order($columns)`
- `limit($limit = null, $offset = null)`
- `select($columns)`
- `where($conditions, ...$args)`
- `orWhere($conditions)`
- `having($conditions, ...$args)`
- `orHaving($conditions)`
- `clear($clause = null)`
- `bind($key = null, $value = null, $dataType = \PDO::PARAM_STR, $length = 0, $driverOptions = array())`

See [Query Format](https://github.com/ventoviro/windwalker-query#format)

Create Records
--------------

[](#create-records)

Using DataSet to wrap every data, then send this object to create() method, these data will insert to table.

### create()

[](#create)

```
use Windwalker\Data\Data;
use Windwalker\Data\DataSet;

$data1 = new Data;
$data1->title = 'Foo';
$data1->auhor = 'Magneto';

$data2 = new Data(
    array(
        'title' => 'Bar',
        'author' => 'Wolverine'
    )
);

$dataset = new DataSet(array($data1, $data2));

$return = $fooMapper->create($dataset);
```

The return value will be whole dataset and add inserted ids.

```
Windwalker\Data\DataSet Object
(
    [storage:ArrayObject:private] => Array
        (
            [0] => Windwalker\Data\Data Object
                (
                    [title] => Foo
                    [auhor] => Magneto
                    [id] => 39
                )

            [1] => Windwalker\Data\Data Object
                (
                    [title] => Bar
                    [auhor] => Wolverine
                    [id] => 40
                )
        )
)

```

### createOne()

[](#createone)

Only insert one row, do not need DataSet.

```
$data = new Data;
$data->title = 'Foo';
$data->auhor = 'Magneto';

$fooMapper->createOne($data);
```

Update Records
--------------

[](#update-records)

Update methods help us update rows in table.

### update()

[](#update)

```
use Windwalker\Data\Data;
use Windwalker\Data\DataSet;

$data1 = new Data;
$data1->id = 1;
$data1->title = 'Foo';

$data2 = new Data(
    array(
        'id' => 2,
        'title' => 'Bar'
    )
);

$dataset = new DataSet(array($data1, $data2));

$fooMapper->update($dataset);
```

### updateOne()

[](#updateone)

Just update one row.

```
$data = new Data;
$data->id = 1;
$data->title = 'Foo';

$fooMapper->updateOne($data);
```

### updateAll()

[](#updateall)

UpdateAll is different from update method, we just send one data object, but using conditions as where to update every row match these conditions. We don't need primary key for updateAll().

```
$data = new Data;
$data->published = 0;

$fooMapper->updateAll($data, array('author' => 'Mystique'));
```

Delete
------

[](#delete)

Delete rows by conditions.

### delete()

[](#delete-1)

```
$boolean = $fooMapper->delete(array('author' => 'Jean Grey'));
```

Join Tables
-----------

[](#join-tables)

Use `newRelation()` to create a DataMapper and join other tables.

```
use Windwalker\DataMapper\DataMapper;

$items = DataMapper::newRelation('flower', '#__flower')
	->leftJoin('author', '#__users', 'flower.user_id = author.id')
	->innerJoin('category', '#__categories', array('category.lft >= flower.lft', 'category.rgt = foo.lft OR category.rgt
