ComparesRelatedModels.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Relations\Concerns;
  3. use Illuminate\Contracts\Database\Eloquent\SupportsPartialRelations;
  4. use Illuminate\Database\Eloquent\Model;
  5. trait ComparesRelatedModels
  6. {
  7. /**
  8. * Determine if the model is the related instance of the relationship.
  9. *
  10. * @param \Illuminate\Database\Eloquent\Model|null $model
  11. * @return bool
  12. */
  13. public function is($model)
  14. {
  15. $match = ! is_null($model) &&
  16. $this->compareKeys($this->getParentKey(), $this->getRelatedKeyFrom($model)) &&
  17. $this->related->getTable() === $model->getTable() &&
  18. $this->related->getConnectionName() === $model->getConnectionName();
  19. if ($match && $this instanceof SupportsPartialRelations && $this->isOneOfMany()) {
  20. return $this->query
  21. ->whereKey($model->getKey())
  22. ->exists();
  23. }
  24. return $match;
  25. }
  26. /**
  27. * Determine if the model is not the related instance of the relationship.
  28. *
  29. * @param \Illuminate\Database\Eloquent\Model|null $model
  30. * @return bool
  31. */
  32. public function isNot($model)
  33. {
  34. return ! $this->is($model);
  35. }
  36. /**
  37. * Get the value of the parent model's key.
  38. *
  39. * @return mixed
  40. */
  41. abstract public function getParentKey();
  42. /**
  43. * Get the value of the model's related key.
  44. *
  45. * @param \Illuminate\Database\Eloquent\Model $model
  46. * @return mixed
  47. */
  48. abstract protected function getRelatedKeyFrom(Model $model);
  49. /**
  50. * Compare the parent key with the related key.
  51. *
  52. * @param mixed $parentKey
  53. * @param mixed $relatedKey
  54. * @return bool
  55. */
  56. protected function compareKeys($parentKey, $relatedKey)
  57. {
  58. if (empty($parentKey) || empty($relatedKey)) {
  59. return false;
  60. }
  61. if (is_int($parentKey) || is_int($relatedKey)) {
  62. return (int) $parentKey === (int) $relatedKey;
  63. }
  64. return $parentKey === $relatedKey;
  65. }
  66. }