Skip to content

Commit

Permalink
added Join to select queries
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarotero committed Mar 17, 2019
1 parent fb9a3df commit 405a38f
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
vendor
composer.lock
.php_cs.cache
.phpunit.result.cache
coverage
1 change: 0 additions & 1 deletion .phpunit.result.cache

This file was deleted.

65 changes: 65 additions & 0 deletions src/Query/Traits/HasJoin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php
declare(strict_types = 1);

namespace SimpleCrud\Query\Traits;

use InvalidArgumentException;
use RuntimeException;
use SimpleCrud\Row;
use SimpleCrud\RowCollection;
use SimpleCrud\Table;

trait HasJoin
{
public function join(Table $table2, string $condition = null, ...$values)
{
$table1 = $this->table;

//Has One
if ($field = $table1->getJoinField($table2)) {
$this->query
->join(
'LEFT',
(string) $table2,
sprintf('%s = %s', $field, $table2->id)
);

//Has many
} elseif ($field = $table->getJoinField($table1)) {
$this->query
->join(
'LEFT',
(string) $table2,
sprintf('%s = %s', $field, $table1->id)
);

//Has many to many
} elseif ($joinTable = $table1->getJoinTable($table2)) {
$field1 = $joinTable->getJoinField($table1);
$field2 = $joinTable->getJoinField($table2);

$this->query
->join(
'LEFT',
(string) $joinTable,
sprintf('%s = %s', $field1, $table1->id)
)
->join(
'LEFT',
(string) $table2,
sprintf('%s = %s', $field2, $table2->id)
);

} else {
throw new RuntimeException(
sprintf('The tables %s and %s are not related', $table1, $table2)
);
}

if ($condition) {
$this->query->catJoin($condition, $values);
}

return $this;
}
}
2 changes: 2 additions & 0 deletions src/Query/Traits/HasWhere.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

trait HasWhere
{
use HasJoin;

public function where(string $condition, ...$values)
{
$this->query->where($condition, ...$values);
Expand Down

0 comments on commit 405a38f

Please sign in to comment.