1: <?php namespace Laravel\Database\Eloquent\Relationships;
2:
3: class Belongs_To extends Relationship {
4:
5: /**
6: * Get the properly hydrated results for the relationship.
7: *
8: * @return Model
9: */
10: public function results()
11: {
12: return parent::first();
13: }
14:
15: /**
16: * Update the parent model of the relationship.
17: *
18: * @param Model|array $attributes
19: * @return int
20: */
21: public function update($attributes)
22: {
23: $attributes = ($attributes instanceof Model) ? $attributes->get_dirty() : $attributes;
24:
25: return $this->model->update($this->foreign_value(), $attributes);
26: }
27:
28: /**
29: * Set the proper constraints on the relationship table.
30: *
31: * @return void
32: */
33: protected function constrain()
34: {
35: $this->table->where($this->model->key(), '=', $this->foreign_value());
36: }
37:
38: /**
39: * Initialize a relationship on an array of parent models.
40: *
41: * @param array $parents
42: * @param string $relationship
43: * @return void
44: */
45: public function initialize(&$parents, $relationship)
46: {
47: foreach ($parents as &$parent)
48: {
49: $parent->relationships[$relationship] = null;
50: }
51: }
52:
53: /**
54: * Set the proper constraints on the relationship table for an eager load.
55: *
56: * @param array $results
57: * @return void
58: */
59: public function eagerly_constrain($results)
60: {
61: $keys = array();
62:
63: // Inverse one-to-many relationships require us to gather the keys from the
64: // parent models and use those keys when setting the constraint since we
65: // are looking for the parent of a child model in this relationship.
66: foreach ($results as $result)
67: {
68: if ( ! is_null($key = $result->{$this->foreign_key()}))
69: {
70: $keys[] = $key;
71: }
72: }
73:
74: if (count($keys) == 0) $keys = array(0);
75:
76: $this->table->where_in($this->model->key(), array_unique($keys));
77: }
78:
79: /**
80: * Match eagerly loaded child models to their parent models.
81: *
82: * @param array $children
83: * @param array $parents
84: * @return void
85: */
86: public function match($relationship, &$children, $parents)
87: {
88: $foreign = $this->foreign_key();
89:
90: $dictionary = array();
91:
92: foreach ($parents as $parent)
93: {
94: $dictionary[$parent->get_key()] = $parent;
95: }
96:
97: foreach ($children as $child)
98: {
99: if (array_key_exists($child->$foreign, $dictionary))
100: {
101: $child->relationships[$relationship] = $dictionary[$child->$foreign];
102: }
103: }
104: }
105:
106: /**
107: * Get the value of the foreign key from the base model.
108: *
109: * @return mixed
110: */
111: public function foreign_value()
112: {
113: return $this->base->{$this->foreign};
114: }
115:
116: /**
117: * Bind an object over a belongs-to relation using its id.
118: *
119: * @return Eloquent
120: */
121:
122: public function bind($id)
123: {
124: $this->base->fill(array($this->foreign => $id))->save();
125:
126: return $this->base;
127: }
128:
129: }
130: