1: <?php
2:
3: /**
4: * Deep
5: *
6: * @package rsanchez\Deep
7: * @author Rob Sanchez <info@robsanchez.com>
8: */
9:
10: namespace rsanchez\Deep\Model;
11:
12: use rsanchez\Deep\Model\JoinableScope;
13: use Illuminate\Database\Eloquent\Model;
14: use Illuminate\Database\Eloquent\Builder;
15:
16: /**
17: * Model which can optionally join the specified table(s)
18: */
19: trait JoinableTrait
20: {
21: /**
22: * Find a model by its primary key.
23: *
24: * @param mixed $id
25: * @param array $columns
26: * @return \Illuminate\Database\Eloquent\Model|Collection
27: */
28: public static function find($id, $columns = array('*'))
29: {
30: $instance = new static;
31:
32: if (is_array($id) && empty($id)) {
33: return $instance->newCollection();
34: }
35:
36: $query = $instance->newQuery();
37:
38: $key = $instance->table.'.'.$instance->primaryKey;
39:
40: if (is_array($id)) {
41: return $query->whereIn($key, $id)
42: ->get($columns);
43: }
44:
45: return $query->where($key, '=', $id)
46: ->first($columns);
47: }
48:
49: /**
50: * Set the global eloquent scope
51: * @return void
52: */
53: protected static function bootJoinableTrait()
54: {
55: $tables = static::defaultJoinTables();
56:
57: if ($tables) {
58: static::addGlobalScope(new JoinableScope($tables));
59: }
60: }
61:
62: /**
63: * Set which tables should be joined automatically
64: * @return array
65: */
66: public static function defaultJoinTables()
67: {
68: return [];
69: }
70:
71: /**
72: * Return a structured array of joinable tables
73: * ex.
74: * 'members' => array('members.member_id', 'channel_titles.author_id'),
75: *
76: * @return array
77: */
78: protected static function joinTables()
79: {
80: return [];
81: }
82:
83: /**
84: * Join the required table, once
85: *
86: * @param \Illuminate\Database\Eloquent\Builder $builder
87: * @param string $table table name
88: * @return \Illuminate\Database\Eloquent\Builder $builder
89: */
90: public function requireTable(Builder $builder, $table)
91: {
92: $tables = static::joinTables();
93:
94: if (! isset($tables[$table])) {
95: return $builder;
96: }
97:
98: $callback = $tables[$table];
99:
100: $query = $builder->getQuery();
101:
102: // don't join twice
103: if ($query->joins) {
104: foreach ($query->joins as $joinClause) {
105: if ($joinClause->table === $table) {
106: return $builder;
107: }
108: }
109: }
110:
111: $callback($builder);
112:
113: return $builder;
114: }
115: }
116: