1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace OfflineAgency\MongoAutoSync\Eloquent; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Str; |
6
|
|
|
use OfflineAgency\MongoAutoSync\Relationships\EmbedsMany; |
7
|
|
|
use OfflineAgency\MongoAutoSync\Relationships\EmbedsOne; |
8
|
|
|
|
9
|
|
|
trait EmbedsRelationships |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Define an embedded one-to-many relationship. |
13
|
|
|
* @param string $related |
14
|
|
|
* @param string $localKey |
15
|
|
|
* @param string $foreignKey |
16
|
|
|
* @param string $relation |
17
|
|
|
* @return EmbedsMany |
18
|
|
|
*/ |
19
|
|
|
protected function embedsMany($related, $localKey = null, $foreignKey = null, $relation = null) |
20
|
|
|
{ |
21
|
|
|
// If no relation name was given, we will use this debug backtrace to extract |
22
|
|
|
// the calling method's name and use that as the relationship name as most |
23
|
|
|
// of the time this will be what we desire to use for the relationships. |
24
|
|
|
if ($relation === null) { |
25
|
|
|
[, $caller] = debug_backtrace(false); |
|
|
|
|
26
|
|
|
|
27
|
|
|
$relation = $caller['function']; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
if ($localKey === null) { |
31
|
|
|
$localKey = $relation; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
if ($foreignKey === null) { |
35
|
|
|
$foreignKey = Str::snake(class_basename($this)); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$query = $this->newQuery(); |
|
|
|
|
39
|
|
|
|
40
|
|
|
$instance = new $related; |
41
|
|
|
|
42
|
|
|
return new EmbedsMany($query, $this, $instance, $localKey, $foreignKey, $relation); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Define an embedded one-to-many relationship. |
47
|
|
|
* @param string $related |
48
|
|
|
* @param string $localKey |
49
|
|
|
* @param string $foreignKey |
50
|
|
|
* @param string $relation |
51
|
|
|
* @return EmbedsOne |
52
|
|
|
*/ |
53
|
|
|
protected function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null) |
54
|
|
|
{ |
55
|
|
|
// If no relation name was given, we will use this debug backtrace to extract |
56
|
|
|
// the calling method's name and use that as the relationship name as most |
57
|
|
|
// of the time this will be what we desire to use for the relationships. |
58
|
|
|
if ($relation === null) { |
59
|
|
|
[, $caller] = debug_backtrace(false); |
|
|
|
|
60
|
|
|
|
61
|
|
|
$relation = $caller['function']; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
if ($localKey === null) { |
65
|
|
|
$localKey = $relation; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if ($foreignKey === null) { |
69
|
|
|
$foreignKey = Str::snake(class_basename($this)); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$query = $this->newQuery(); |
73
|
|
|
|
74
|
|
|
$instance = new $related; |
75
|
|
|
|
76
|
|
|
return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation); |
|
|
|
|
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|