From 804b4698f0da377b43a87cbd0ebce3404f5de9e5 Mon Sep 17 00:00:00 2001 From: hackerESQ Date: Sat, 10 Aug 2024 13:30:28 -0500 Subject: [PATCH] add composite key trait --- app/Traits/HasCompositePrimaryKey.php | 53 +++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 app/Traits/HasCompositePrimaryKey.php diff --git a/app/Traits/HasCompositePrimaryKey.php b/app/Traits/HasCompositePrimaryKey.php new file mode 100644 index 0000000..f2af335 --- /dev/null +++ b/app/Traits/HasCompositePrimaryKey.php @@ -0,0 +1,53 @@ +getKeyName() as $key) { + // UPDATE: Added isset() per devflow's comment. + if (isset($this->$key)) + $query->where($key, '=', $this->$key); + else + throw new \Exception(__METHOD__ . 'Missing part of the primary key: ' . $key); + } + + return $query; + } + + // UPDATE: From jessedp. See his edit, below. + /** + * Execute a query for a single record by ID. + * + * @param array $ids Array of keys, like [column => value]. + * @param array $columns + * @return mixed|static + */ + public static function find($ids, $columns = ['*']) + { + $me = new self; + $query = $me->newQuery(); + foreach ($me->getKeyName() as $key) { + $query->where($key, '=', $ids[$key]); + } + return $query->first($columns); + } +} \ No newline at end of file