1: <?php namespace Laravel\Database\Eloquent\Relationships;
2:
3: class Has_Many extends Has_One_Or_Many {
4:
5: /**
6: * Get the properly hydrated results for the relationship.
7: *
8: * @return array
9: */
10: public function results()
11: {
12: return parent::get();
13: }
14:
15: /**
16: * Sync the association table with an array of models.
17: *
18: * @param mixed $models
19: * @return bool
20: */
21: public function save($models)
22: {
23: // If the given "models" are not an array, we'll force them into an array so
24: // we can conveniently loop through them and insert all of them into the
25: // related database table assigned to the associated model instance.
26: if ( ! is_array($models)) $models = array($models);
27:
28: $current = $this->table->lists($this->model->key());
29:
30: foreach ($models as $attributes)
31: {
32: $class = get_class($this->model);
33:
34: // If the "attributes" are actually an array of the related model we'll
35: // just use the existing instance instead of creating a fresh model
36: // instance for the attributes. This allows for validation.
37: if ($attributes instanceof $class)
38: {
39: $model = $attributes;
40: }
41: else
42: {
43: $model = $this->fresh_model($attributes);
44: }
45:
46: // We'll need to associate the model with its parent, so we'll set the
47: // foreign key on the model to the key of the parent model, making
48: // sure that the two models are associated in the database.
49: $foreign = $this->foreign_key();
50:
51: $model->$foreign = $this->base->get_key();
52:
53: $id = $model->get_key();
54:
55: $model->exists = ( ! is_null($id) and in_array($id, $current));
56:
57: // Before saving we'll force the entire model to be "dirty" so all of
58: // the attributes are saved. It shouldn't affect the updates as
59: // saving all the attributes shouldn't hurt anything.
60: $model->original = array();
61:
62: $model->save();
63: }
64:
65: return true;
66: }
67:
68: /**
69: * Initialize a relationship on an array of parent models.
70: *
71: * @param array $parents
72: * @param string $relationship
73: * @return void
74: */
75: public function initialize(&$parents, $relationship)
76: {
77: foreach ($parents as &$parent)
78: {
79: $parent->relationships[$relationship] = array();
80: }
81: }
82:
83: /**
84: * Match eagerly loaded child models to their parent models.
85: *
86: * @param array $parents
87: * @param array $children
88: * @return void
89: */
90: public function match($relationship, &$parents, $children)
91: {
92: $foreign = $this->foreign_key();
93:
94: $dictionary = array();
95:
96: foreach ($children as $child)
97: {
98: $dictionary[$child->$foreign][] = $child;
99: }
100:
101: foreach ($parents as $parent)
102: {
103: if (array_key_exists($key = $parent->get_key(), $dictionary))
104: {
105: $parent->relationships[$relationship] = $dictionary[$key];
106: }
107: }
108: }
109:
110: }