has_many_and_belongs_to.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 attach($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 Model|array $attributes
  78. * @param array $joining
  79. * @return bool
  80. */
  81. public function insert($attributes, $joining = array())
  82. {
  83. // If the attributes are actually an instance of a model, we'll just grab the
  84. // array of attributes off of the model for saving, allowing the developer
  85. // to easily validate the joining models before inserting them.
  86. if ($attributes instanceof Model)
  87. {
  88. $attributes = $attributes->attributes;
  89. }
  90. $model = $this->model->create($attributes);
  91. // If the insert was successful, we'll insert a record into the joining table
  92. // using the new ID that was just inserted into the related table, allowing
  93. // the developer to not worry about maintaining the join table.
  94. if ($model instanceof Model)
  95. {
  96. $joining = array_merge($this->join_record($model->get_key()), $joining);
  97. $result = $this->insert_joining($joining);
  98. }
  99. return $model instanceof Model and $result;
  100. }
  101. /**
  102. * Delete all of the records from the joining table for the model.
  103. *
  104. * @return int
  105. */
  106. public function delete()
  107. {
  108. $id = $this->base->get_key();
  109. return $this->joining_table()->where($this->foreign_key(), '=', $id)->delete();
  110. }
  111. /**
  112. * Create an array representing a new joining record for the association.
  113. *
  114. * @param int $id
  115. * @return array
  116. */
  117. protected function join_record($id)
  118. {
  119. return array($this->foreign_key() => $this->base->get_key(), $this->other_key() => $id);
  120. }
  121. /**
  122. * Insert a new record into the joining table of the association.
  123. *
  124. * @param array $attributes
  125. * @return void
  126. */
  127. protected function insert_joining($attributes)
  128. {
  129. $attributes['created_at'] = $this->model->get_timestamp();
  130. $attributes['updated_at'] = $attributes['created_at'];
  131. return $this->joining_table()->insert($attributes);
  132. }
  133. /**
  134. * Get a fluent query for the joining table of the relationship.
  135. *
  136. * @return Query
  137. */
  138. protected function joining_table()
  139. {
  140. return $this->connection()->table($this->joining);
  141. }
  142. /**
  143. * Set the proper constraints on the relationship table.
  144. *
  145. * @return void
  146. */
  147. protected function constrain()
  148. {
  149. $other = $this->other_key();
  150. $foreign = $this->foreign_key();
  151. $this->set_select($foreign, $other)->set_join($other)->set_where($foreign);
  152. }
  153. /**
  154. * Set the SELECT clause on the query builder for the relationship.
  155. *
  156. * @param string $foreign
  157. * @param string $other
  158. * @return void
  159. */
  160. protected function set_select($foreign, $other)
  161. {
  162. $columns = array($this->model->table().'.*');
  163. $this->with = array_merge($this->with, array($foreign, $other));
  164. // Since pivot tables may have extra information on them that the developer
  165. // needs, we allow an extra array of columns to be specified that will be
  166. // fetched from the pivot table and hydrate into the pivot model.
  167. foreach ($this->with as $column)
  168. {
  169. $columns[] = $this->joining.'.'.$column.' as pivot_'.$column;
  170. }
  171. $this->table->select($columns);
  172. return $this;
  173. }
  174. /**
  175. * Set the JOIN clause on the query builder for the relationship.
  176. *
  177. * @param string $other
  178. * @return void
  179. */
  180. protected function set_join($other)
  181. {
  182. $this->table->join($this->joining, $this->associated_key(), '=', $this->joining.'.'.$other);
  183. return $this;
  184. }
  185. /**
  186. * Set the WHERE clause on the query builder for the relationship.
  187. *
  188. * @param string $foreign
  189. * @return void
  190. */
  191. protected function set_where($foreign)
  192. {
  193. $this->table->where($this->joining.'.'.$foreign, '=', $this->base->get_key());
  194. return $this;
  195. }
  196. /**
  197. * Initialize a relationship on an array of parent models.
  198. *
  199. * @param array $parents
  200. * @param string $relationship
  201. * @return void
  202. */
  203. public function initialize(&$parents, $relationship)
  204. {
  205. foreach ($parents as &$parent)
  206. {
  207. $parent->relationships[$relationship] = array();
  208. }
  209. }
  210. /**
  211. * Set the proper constraints on the relationship table for an eager load.
  212. *
  213. * @param array $results
  214. * @return void
  215. */
  216. public function eagerly_constrain($results)
  217. {
  218. $this->table->where_in($this->joining.'.'.$this->foreign_key(), array_keys($results));
  219. }
  220. /**
  221. * Match eagerly loaded child models to their parent models.
  222. *
  223. * @param array $parents
  224. * @param array $children
  225. * @return void
  226. */
  227. public function match($relationship, &$parents, $children)
  228. {
  229. $foreign = $this->foreign_key();
  230. foreach ($children as $key => $child)
  231. {
  232. $parents[$child->pivot->$foreign]->relationships[$relationship][$child->{$child->key()}] = $child;
  233. }
  234. }
  235. /**
  236. * Hydrate the Pivot model on an array of results.
  237. *
  238. * @param array $results
  239. * @return void
  240. */
  241. protected function hydrate_pivot(&$results)
  242. {
  243. foreach ($results as &$result)
  244. {
  245. // Every model result for a many-to-many relationship needs a Pivot instance
  246. // to represent the pivot table's columns. Sometimes extra columns are on
  247. // the pivot table that may need to be accessed by the developer.
  248. $pivot = new Pivot($this->joining);
  249. $attributes = array_filter($result->attributes, function($attribute)
  250. {
  251. return starts_with($attribute, 'pivot_');
  252. });
  253. // If the attribute key starts with "pivot_", we know this is a column on
  254. // the pivot table, so we will move it to the Pivot model and purge it
  255. // from the model since it actually belongs to the pivot.
  256. foreach ($attributes as $key => $value)
  257. {
  258. $pivot->{substr($key, 6)} = $value;
  259. $result->purge($key);
  260. }
  261. // Once we have completed hydrating the pivot model instance, we'll set
  262. // it on the result model's relationships array so the developer can
  263. // quickly and easily access any pivot table information.
  264. $result->relationships['pivot'] = $pivot;
  265. $pivot->sync() and $result->sync();
  266. }
  267. }
  268. /**
  269. * Set the columns on the joining table that should be fetched.
  270. *
  271. * @param array $column
  272. * @return Relationship
  273. */
  274. public function with($columns)
  275. {
  276. $columns = (is_array($columns)) ? $columns : func_get_args();
  277. // The "with" array contains a couple of columns by default, so we will
  278. // just merge in the developer specified columns here, and we'll make
  279. // sure the values of the array are unique.
  280. $this->with = array_unique(array_merge($this->with, $columns));
  281. $this->set_select($this->foreign_key(), $this->other_key());
  282. return $this;
  283. }
  284. /**
  285. * Get a model instance of the pivot table for the relationship.
  286. *
  287. * @return Pivot
  288. */
  289. public function pivot()
  290. {
  291. $key = $this->base->get_key();
  292. $foreign = $this->foreign_key();
  293. return with(new Pivot($this->joining))->where($foreign, '=', $key);
  294. }
  295. /**
  296. * Get the other or associated key for the relationship.
  297. *
  298. * @return string
  299. */
  300. protected function other_key()
  301. {
  302. return Relationship::foreign($this->model, $this->other);
  303. }
  304. /**
  305. * Get the fully qualified associated table's primary key.
  306. *
  307. * @return string
  308. */
  309. protected function associated_key()
  310. {
  311. return $this->model->table().'.'.$this->model->key();
  312. }
  313. }