has_many_and_belongs_to.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 table that should be fetched.
  20. *
  21. * @var array
  22. */
  23. protected $with = array('id');
  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. // If the Pivot table is timestamped, we'll set the timestamp columns to be
  39. // fetched when the pivot table models are fetched by the developer else
  40. // the ID will be the only "extra" column fetched in by default.
  41. if (Pivot::$timestamps)
  42. {
  43. $this->with[] = 'created_at';
  44. $this->with[] = 'updated_at';
  45. }
  46. parent::__construct($model, $associated, $foreign);
  47. }
  48. /**
  49. * Determine the joining table name for the relationship.
  50. *
  51. * By default, the name is the models sorted and joined with underscores.
  52. *
  53. * @return string
  54. */
  55. protected function joining($model, $associated)
  56. {
  57. $models = array(class_basename($model), class_basename($associated));
  58. sort($models);
  59. return strtolower($models[0].'_'.$models[1]);
  60. }
  61. /**
  62. * Get the properly hydrated results for the relationship.
  63. *
  64. * @return array
  65. */
  66. public function results()
  67. {
  68. return parent::get();
  69. }
  70. /**
  71. * Insert a new record into the joining table of the association.
  72. *
  73. * @param int $id
  74. * @param array $joining
  75. * @return bool
  76. */
  77. public function attach($id, $attributes = array())
  78. {
  79. $joining = array_merge($this->join_record($id), $attributes);
  80. return $this->insert_joining($joining);
  81. }
  82. /**
  83. * Detach a record from the joining table of the association.
  84. *
  85. * @param int $ids
  86. * @return bool
  87. */
  88. public function detach($ids)
  89. {
  90. if ( ! is_array($ids)) $ids = array($ids);
  91. return $this->pivot()->where_in($this->other_key(), $ids)->delete();
  92. }
  93. /**
  94. * Sync the joining table with the array of given IDs.
  95. *
  96. * @param array $ids
  97. * @return bool
  98. */
  99. public function sync($ids)
  100. {
  101. $current = $this->pivot()->lists($this->other_key());
  102. // First we need to attach any of the associated models that are not currently
  103. // in the joining table. We'll spin through the given IDs, checking to see
  104. // if they exist in the array of current ones, and if not we insert.
  105. foreach ($ids as $id)
  106. {
  107. if ( ! in_array($id, $current))
  108. {
  109. $this->attach($id);
  110. }
  111. }
  112. // Next we will take the difference of the current and given IDs and detach
  113. // all of the entities that exists in the current array but are not in
  114. // the array of IDs given to the method, finishing the sync.
  115. $detach = array_diff($current, $ids);
  116. if (count($detach) > 0)
  117. {
  118. $this->detach(array_diff($current, $ids));
  119. }
  120. }
  121. /**
  122. * Insert a new record for the association.
  123. *
  124. * @param Model|array $attributes
  125. * @param array $joining
  126. * @return bool
  127. */
  128. public function insert($attributes, $joining = array())
  129. {
  130. // If the attributes are actually an instance of a model, we'll just grab the
  131. // array of attributes off of the model for saving, allowing the developer
  132. // to easily validate the joining models before inserting them.
  133. if ($attributes instanceof Model)
  134. {
  135. $attributes = $attributes->attributes;
  136. }
  137. $model = $this->model->create($attributes);
  138. // If the insert was successful, we'll insert a record into the joining table
  139. // using the new ID that was just inserted into the related table, allowing
  140. // the developer to not worry about maintaining the join table.
  141. if ($model instanceof Model)
  142. {
  143. $joining = array_merge($this->join_record($model->get_key()), $joining);
  144. $result = $this->insert_joining($joining);
  145. }
  146. return $model instanceof Model and $result;
  147. }
  148. /**
  149. * Delete all of the records from the joining table for the model.
  150. *
  151. * @return int
  152. */
  153. public function delete()
  154. {
  155. return $this->pivot()->delete();
  156. }
  157. /**
  158. * Create an array representing a new joining record for the association.
  159. *
  160. * @param int $id
  161. * @return array
  162. */
  163. protected function join_record($id)
  164. {
  165. return array($this->foreign_key() => $this->base->get_key(), $this->other_key() => $id);
  166. }
  167. /**
  168. * Insert a new record into the joining table of the association.
  169. *
  170. * @param array $attributes
  171. * @return void
  172. */
  173. protected function insert_joining($attributes)
  174. {
  175. if (Pivot::$timestamps)
  176. {
  177. $attributes['created_at'] = new \DateTime;
  178. $attributes['updated_at'] = $attributes['created_at'];
  179. }
  180. return $this->joining_table()->insert($attributes);
  181. }
  182. /**
  183. * Get a fluent query for the joining table of the relationship.
  184. *
  185. * @return Query
  186. */
  187. protected function joining_table()
  188. {
  189. return $this->connection()->table($this->joining);
  190. }
  191. /**
  192. * Set the proper constraints on the relationship table.
  193. *
  194. * @return void
  195. */
  196. protected function constrain()
  197. {
  198. $other = $this->other_key();
  199. $foreign = $this->foreign_key();
  200. $this->set_select($foreign, $other)->set_join($other)->set_where($foreign);
  201. }
  202. /**
  203. * Set the SELECT clause on the query builder for the relationship.
  204. *
  205. * @param string $foreign
  206. * @param string $other
  207. * @return void
  208. */
  209. protected function set_select($foreign, $other)
  210. {
  211. $columns = array($this->model->table().'.*');
  212. $this->with = array_merge($this->with, array($foreign, $other));
  213. // Since pivot tables may have extra information on them that the developer
  214. // needs we allow an extra array of columns to be specified that will be
  215. // fetched from the pivot table and hydrate into the pivot model.
  216. foreach ($this->with as $column)
  217. {
  218. $columns[] = $this->joining.'.'.$column.' as pivot_'.$column;
  219. }
  220. $this->table->select($columns);
  221. return $this;
  222. }
  223. /**
  224. * Set the JOIN clause on the query builder for the relationship.
  225. *
  226. * @param string $other
  227. * @return void
  228. */
  229. protected function set_join($other)
  230. {
  231. $this->table->join($this->joining, $this->associated_key(), '=', $this->joining.'.'.$other);
  232. return $this;
  233. }
  234. /**
  235. * Set the WHERE clause on the query builder for the relationship.
  236. *
  237. * @param string $foreign
  238. * @return void
  239. */
  240. protected function set_where($foreign)
  241. {
  242. $this->table->where($this->joining.'.'.$foreign, '=', $this->base->get_key());
  243. return $this;
  244. }
  245. /**
  246. * Initialize a relationship on an array of parent models.
  247. *
  248. * @param array $parents
  249. * @param string $relationship
  250. * @return void
  251. */
  252. public function initialize(&$parents, $relationship)
  253. {
  254. foreach ($parents as &$parent)
  255. {
  256. $parent->relationships[$relationship] = array();
  257. }
  258. }
  259. /**
  260. * Set the proper constraints on the relationship table for an eager load.
  261. *
  262. * @param array $results
  263. * @return void
  264. */
  265. public function eagerly_constrain($results)
  266. {
  267. $this->table->where_in($this->joining.'.'.$this->foreign_key(), $this->keys($results));
  268. }
  269. /**
  270. * Match eagerly loaded child models to their parent models.
  271. *
  272. * @param array $parents
  273. * @param array $children
  274. * @return void
  275. */
  276. public function match($relationship, &$parents, $children)
  277. {
  278. $foreign = $this->foreign_key();
  279. foreach ($parents as &$parent)
  280. {
  281. $matching = array_filter($children, function($v) use ($parent, $foreign)
  282. {
  283. return $v->pivot->$foreign == $parent->get_key();
  284. });
  285. $parent->relationships[$relationship] = array_values($matching);
  286. }
  287. }
  288. /**
  289. * Hydrate the Pivot model on an array of results.
  290. *
  291. * @param array $results
  292. * @return void
  293. */
  294. protected function hydrate_pivot(&$results)
  295. {
  296. foreach ($results as &$result)
  297. {
  298. // Every model result for a many-to-many relationship needs a Pivot instance
  299. // to represent the pivot table's columns. Sometimes extra columns are on
  300. // the pivot table that may need to be accessed by the developer.
  301. $pivot = new Pivot($this->joining);
  302. // If the attribute key starts with "pivot_", we know this is a column on
  303. // the pivot table, so we will move it to the Pivot model and purge it
  304. // from the model since it actually belongs to the pivot model.
  305. foreach ($result->attributes as $key => $value)
  306. {
  307. if (starts_with($key, 'pivot_'))
  308. {
  309. $pivot->{substr($key, 6)} = $value;
  310. $result->purge($key);
  311. }
  312. }
  313. // Once we have completed hydrating the pivot model instance, we'll set
  314. // it on the result model's relationships array so the developer can
  315. // quickly and easily access any pivot table information.
  316. $result->relationships['pivot'] = $pivot;
  317. $pivot->sync() and $result->sync();
  318. }
  319. }
  320. /**
  321. * Set the columns on the joining table that should be fetched.
  322. *
  323. * @param array $column
  324. * @return Relationship
  325. */
  326. public function with($columns)
  327. {
  328. $columns = (is_array($columns)) ? $columns : func_get_args();
  329. // The "with" array contains a couple of columns by default, so we will just
  330. // merge in the developer specified columns here, and we will make sure
  331. // the values of the array are unique to avoid duplicates.
  332. $this->with = array_unique(array_merge($this->with, $columns));
  333. $this->set_select($this->foreign_key(), $this->other_key());
  334. return $this;
  335. }
  336. /**
  337. * Get a relationship instance of the pivot table.
  338. *
  339. * @return Has_Many
  340. */
  341. public function pivot()
  342. {
  343. return new Has_Many($this->base, new Pivot($this->joining), $this->foreign_key());
  344. }
  345. /**
  346. * Get the other or associated key for the relationship.
  347. *
  348. * @return string
  349. */
  350. protected function other_key()
  351. {
  352. return Relationship::foreign($this->model, $this->other);
  353. }
  354. /**
  355. * Get the fully qualified associated table's primary key.
  356. *
  357. * @return string
  358. */
  359. protected function associated_key()
  360. {
  361. return $this->model->table().'.'.$this->model->key();
  362. }
  363. }