has_many_and_belongs_to.php 10 KB

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