has_many_and_belongs_to.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 Model|int $id
  74. * @param array $attributes
  75. * @return bool
  76. */
  77. public function attach($id, $attributes = array())
  78. {
  79. if ($id instanceof Model) $id = $id->get_key();
  80. $joining = array_merge($this->join_record($id), $attributes);
  81. return $this->insert_joining($joining);
  82. }
  83. /**
  84. * Detach a record from the joining table of the association.
  85. *
  86. * @param array|Model|int $ids
  87. * @return bool
  88. */
  89. public function detach($ids)
  90. {
  91. if ($ids instanceof Model) $ids = array($ids->get_key());
  92. elseif ( ! 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 exists 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 array $parents
  275. * @param array $children
  276. * @return void
  277. */
  278. public function match($relationship, &$parents, $children)
  279. {
  280. $foreign = $this->foreign_key();
  281. $dictionary = array();
  282. foreach ($children as $child)
  283. {
  284. $dictionary[$child->pivot->$foreign][] = $child;
  285. }
  286. foreach ($parents as $parent)
  287. {
  288. if (array_key_exists($key = $parent->get_key(), $dictionary))
  289. {
  290. $parent->relationships[$relationship] = $dictionary[$key];
  291. }
  292. }
  293. }
  294. /**
  295. * Hydrate the Pivot model on an array of results.
  296. *
  297. * @param array $results
  298. * @return void
  299. */
  300. protected function hydrate_pivot(&$results)
  301. {
  302. foreach ($results as &$result)
  303. {
  304. // Every model result for a many-to-many relationship needs a Pivot instance
  305. // to represent the pivot table's columns. Sometimes extra columns are on
  306. // the pivot table that may need to be accessed by the developer.
  307. $pivot = new Pivot($this->joining, $this->model->connection());
  308. // If the attribute key starts with "pivot_", we know this is a column on
  309. // the pivot table, so we will move it to the Pivot model and purge it
  310. // from the model since it actually belongs to the pivot model.
  311. foreach ($result->attributes as $key => $value)
  312. {
  313. if (starts_with($key, 'pivot_'))
  314. {
  315. $pivot->{substr($key, 6)} = $value;
  316. $result->purge($key);
  317. }
  318. }
  319. // Once we have completed hydrating the pivot model instance, we'll set
  320. // it on the result model's relationships array so the developer can
  321. // quickly and easily access any pivot table information.
  322. $result->relationships['pivot'] = $pivot;
  323. $pivot->sync() and $result->sync();
  324. }
  325. }
  326. /**
  327. * Set the columns on the joining table that should be fetched.
  328. *
  329. * @param array $column
  330. * @return Relationship
  331. */
  332. public function with($columns)
  333. {
  334. $columns = (is_array($columns)) ? $columns : func_get_args();
  335. // The "with" array contains a couple of columns by default, so we will just
  336. // merge in the developer specified columns here, and we will make sure
  337. // the values of the array are unique to avoid duplicates.
  338. $this->with = array_unique(array_merge($this->with, $columns));
  339. $this->set_select($this->foreign_key(), $this->other_key());
  340. return $this;
  341. }
  342. /**
  343. * Get a relationship instance of the pivot table.
  344. *
  345. * @return Has_Many
  346. */
  347. public function pivot()
  348. {
  349. $pivot = new Pivot($this->joining, $this->model->connection());
  350. return new Has_Many($this->base, $pivot, $this->foreign_key());
  351. }
  352. /**
  353. * Get the other or associated key for the relationship.
  354. *
  355. * @return string
  356. */
  357. protected function other_key()
  358. {
  359. return Relationship::foreign($this->model, $this->other);
  360. }
  361. /**
  362. * Get the fully qualified associated table's primary key.
  363. *
  364. * @return string
  365. */
  366. protected function associated_key()
  367. {
  368. return $this->model->table().'.'.$this->model->key();
  369. }
  370. }