1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HexMakina\Crudites\Grammar\Clause; |
4
|
|
|
|
5
|
|
|
use HexMakina\Crudites\Grammar\Predicate; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* LEFT JOIN, two ways |
9
|
|
|
* (new Join('cbx_order', 'Orders'))->on('user_id', 'User', 'id')->type('LEFT'); |
10
|
|
|
* (new Join('cbx_order', 'Orders'))->on('user_id', 'User', 'id')->left(); |
11
|
|
|
|
12
|
|
|
* INNER JOIN, with helper, before on |
13
|
|
|
* (new Join('cbx_order', 'Orders'))->inner()->on('user_id', 'User', 'id'); |
14
|
|
|
*/ |
15
|
|
|
|
16
|
|
|
class Join extends Clause |
17
|
|
|
{ |
18
|
|
|
protected string $type; |
19
|
|
|
|
20
|
|
|
protected string $table; |
21
|
|
|
protected string $alias; |
22
|
|
|
|
23
|
|
|
protected string $on = null; |
24
|
|
|
|
25
|
|
|
public function __construct(string $table, string $alias = null) |
26
|
|
|
{ |
27
|
|
|
$this->type = ''; |
28
|
|
|
$this->table = $table; |
29
|
|
|
$this->alias = $alias ?? $table; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function type(string $join_type): self |
33
|
|
|
{ |
34
|
|
|
$this->type = $join_type; |
35
|
|
|
|
36
|
|
|
return $this; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function on($column, $join_table, $join_column): self |
40
|
|
|
{ |
41
|
|
|
$this->on = (string)(new Predicate([$this->alias, $column], '=', [$join_table, $join_column])); |
42
|
|
|
|
43
|
|
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function alias(): string |
47
|
|
|
{ |
48
|
|
|
return $this->alias; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function table(): string |
52
|
|
|
{ |
53
|
|
|
return $this->table; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function __toString(): string |
57
|
|
|
{ |
58
|
|
|
return sprintf('%s JOIN `%s` %s ON %s', $this->type, $this->table, $this->alias, $this->on); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function name(): string |
62
|
|
|
{ |
63
|
|
|
return self::JOIN; |
64
|
|
|
} |
65
|
|
|
} |