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