has_many_and_belongs_to.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php namespace Laravel\Database\Eloquent\Relationships;
  2. use Laravel\Str;
  3. use Laravel\Database\Eloquent\Model;
  4. use Laravel\Database\Eloquent\Pivot;
  5. class Has_Many_And_Belongs_To extends Relationship {
  6. /**
  7. * The name of the intermediate, joining table.
  8. *
  9. * @var string
  10. */
  11. protected $joining;
  12. /**
  13. * The other or "associated" key. This is the foreign key of the related model.
  14. *
  15. * @var string
  16. */
  17. protected $other;
  18. /**
  19. * The columns on the joining tbale that should be fetched.
  20. *
  21. * @var array
  22. */
  23. protected $with = array('id', 'created_at', 'updated_at');
  24. /**
  25. * Create a new many to many relationship instance.
  26. *
  27. * @param Model $model
  28. * @param string $associated
  29. * @param string $table
  30. * @param string $foreign
  31. * @param string $other
  32. * @return void
  33. */
  34. public function __construct($model, $associated, $table, $foreign, $other)
  35. {
  36. $this->other = $other;
  37. $this->joining = $table ?: $this->joining($model, $associated);
  38. parent::__construct($model, $associated, $foreign);
  39. }
  40. /**
  41. * Determine the joining table name for the relationship.
  42. *
  43. * By default, the name is the models sorted and joined with underscores.
  44. *
  45. * @return string
  46. */
  47. protected function joining($model, $associated)
  48. {
  49. $models = array(class_basename($model), class_basename($associated));
  50. sort($models);
  51. return strtolower($models[0].'_'.$models[1]);
  52. }
  53. /**
  54. * Get the properly hydrated results for the relationship.
  55. *
  56. * @return array
  57. */
  58. public function results()
  59. {
  60. return parent::get();
  61. }
  62. /**
  63. * Insert a new record into the joining table of the association.
  64. *
  65. * @param int $id
  66. * @param array $joining
  67. * @return bool
  68. */
  69. public function add($id, $attributes = array())
  70. {
  71. $joining = array_merge($this->join_record($id), $attributes);
  72. return $this->insert_joining($joining);
  73. }
  74. /**
  75. * Insert a new record for the association.
  76. *
  77. * @param array $attributes
  78. * @param array $joining
  79. * @return bool
  80. */
  81. public function insert($attributes, $joining = array())
  82. {
  83. $model = $this->model->create($attributes);
  84. // If the insert was successful, we'll insert a record into the joining table
  85. // using the new ID that was just inserted into the related table, allowing
  86. // the developer to not worry about maintaining the join table.
  87. if ($model instanceof Model and is_numeric($id = $model->get_key()))
  88. {
  89. $result = $this->insert_joining(array_merge($this->join_record($id), $joining));
  90. }
  91. return $model instanceof Model and $result;
  92. }
  93. /**
  94. * Delete all of the records from the joining table for the model.
  95. *
  96. * @return int
  97. */
  98. public function delete()
  99. {
  100. $id = $this->base->get_key();
  101. return $this->joining_table()->where($this->foreign_key(), '=', $id)->delete();
  102. }
  103. /**
  104. * Create an array representing a new joining record for the association.
  105. *
  106. * @param int $id
  107. * @return array
  108. */
  109. protected function join_record($id)
  110. {
  111. return array($this->foreign_key() => $this->base->get_key(), $this->other_key() => $id);
  112. }
  113. /**
  114. * Insert a new record into the joining table of the association.
  115. *
  116. * @param array $attributes
  117. * @return void
  118. */
  119. protected function insert_joining($attributes)
  120. {
  121. // All joining tables get creation and update timestamps automatically even though
  122. // some developers may not need them. This just provides them if necessary since
  123. // it would be a pain for the developer to maintain them each manually.
  124. $attributes['created_at'] = $this->model->get_timestamp();
  125. $attributes['updated_at'] = $attributes['created_at'];
  126. return $this->joining_table()->insert($attributes);
  127. }
  128. /**
  129. * Get a fluent query for the joining table of the relationship.
  130. *
  131. * @return Query
  132. */
  133. protected function joining_table()
  134. {
  135. return $this->connection()->table($this->joining);
  136. }
  137. /**
  138. * Set the proper constraints on the relationship table.
  139. *
  140. * @return void
  141. */
  142. protected function constrain()
  143. {
  144. $other = $this->other_key();
  145. $foreign = $this->foreign_key();
  146. $this->set_select($foreign, $other)->set_join($other)->set_where($foreign);
  147. }
  148. /**
  149. * Set the SELECT clause on the query builder for the relationship.
  150. *
  151. * @param string $foreign
  152. * @param string $other
  153. * @return void
  154. */
  155. protected function set_select($foreign, $other)
  156. {
  157. $columns = array($this->model->table().'.*');
  158. $this->with = array_merge($this->with, array($foreign, $other));
  159. // Since pivot tables may have extra information on them that the developer
  160. // needs, we allow an extra array of columns to be specified that will be
  161. // fetched from the pivot table and hydrate into the pivot model.
  162. foreach ($this->with as $column)
  163. {
  164. $columns[] = $this->joining.'.'.$column.' as pivot_'.$column;
  165. }
  166. $this->table->select($columns);
  167. return $this;
  168. }
  169. /**
  170. * Set the JOIN clause on the query builder for the relationship.
  171. *
  172. * @param string $other
  173. * @return void
  174. */
  175. protected function set_join($other)
  176. {
  177. $this->table->join($this->joining, $this->associated_key(), '=', $this->joining.'.'.$other);
  178. return $this;
  179. }
  180. /**
  181. * Set the WHERE clause on the query builder for the relationship.
  182. *
  183. * @param string $foreign
  184. * @return void
  185. */
  186. protected function set_where($foreign)
  187. {
  188. $this->table->where($this->joining.'.'.$foreign, '=', $this->base->get_key());
  189. return $this;
  190. }
  191. /**
  192. * Initialize a relationship on an array of parent models.
  193. *
  194. * @param array $parents
  195. * @param string $relationship
  196. * @return void
  197. */
  198. public function initialize(&$parents, $relationship)
  199. {
  200. foreach ($parents as &$parent)
  201. {
  202. $parent->relationships[$relationship] = array();
  203. }
  204. }
  205. /**
  206. * Set the proper constraints on the relationship table for an eager load.
  207. *
  208. * @param array $results
  209. * @return void
  210. */
  211. public function eagerly_constrain($results)
  212. {
  213. $this->table->where_in($this->joining.'.'.$this->foreign_key(), array_keys($results));
  214. }
  215. /**
  216. * Match eagerly loaded child models to their parent models.
  217. *
  218. * @param array $parents
  219. * @param array $children
  220. * @return void
  221. */
  222. public function match($relationship, &$parents, $children)
  223. {
  224. $foreign = $this->foreign_key();
  225. foreach ($children as $key => $child)
  226. {
  227. $parents[$child->pivot->$foreign]->relationships[$relationship][$child->{$child->key()}] = $child;
  228. }
  229. }
  230. /**
  231. * Hydrate the Pivot model on an array of results.
  232. *
  233. * @param array $results
  234. * @return void
  235. */
  236. protected function pivot(&$results)
  237. {
  238. foreach ($results as &$result)
  239. {
  240. // Every model result for a many-to-many relationship needs a Pivot instance
  241. // to represent the pivot table's columns. Sometimes extra columns are on
  242. // the pivot table that may need to be accessed by the developer.
  243. $pivot = new Pivot($this->joining);
  244. // If the attribute key starts with "pivot_", we know this is a column on
  245. // the pivot table, so we will move it to the Pivot model and purge it
  246. // from the model since it actually belongs to the pivot.
  247. foreach ($result->attributes as $key => $value)
  248. {
  249. if (starts_with($key, 'pivot_'))
  250. {
  251. $pivot->{substr($key, 6)} = $value;
  252. $result->purge($key);
  253. }
  254. }
  255. // Once we have completed hydrating the pivot model instance, we'll set
  256. // it on the result model's relationships array so the developer can
  257. // quickly and easily access any pivot table information.
  258. $result->relationships['pivot'] = $pivot;
  259. $pivot->sync() and $result->sync();
  260. }
  261. }
  262. /**
  263. * Set the columns on the joining table that should be fetched.
  264. *
  265. * @param array $column
  266. * @return Relationship
  267. */
  268. public function with($columns)
  269. {
  270. $columns = (is_array($columns)) ? $columns : func_get_args();
  271. // The "with" array contains a couple of columns by default, so we will
  272. // just merge in the developer specified columns here, and we'll make
  273. // sure the values of the array are unique.
  274. $this->with = array_unique(array_merge($this->with, $columns));
  275. $this->set_select($this->foreign_key(), $this->other_key());
  276. return $this;
  277. }
  278. /**
  279. * Get the other or associated key for the relationship.
  280. *
  281. * @return string
  282. */
  283. protected function other_key()
  284. {
  285. return Relationship::foreign($this->model, $this->other);
  286. }
  287. /**
  288. * Get the fully qualified associated table's primary key.
  289. *
  290. * @return string
  291. */
  292. protected function associated_key()
  293. {
  294. return $this->model->table().'.'.$this->model->key();
  295. }
  296. }