我写了这个简单的PHP特性,以使Eloquent能够处理复合键:
<?phpnamespace AppModelTraits; // *** Adjust this to match your model namespace! ***use IlluminateDatabaseEloquentBuilder;trait HasCompositePrimaryKey{ public function getIncrementing() { return false; } protected function setKeysForSaveQuery(Builder $query) { foreach ($this->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. 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); }}
将其放置在
Traits主模型目录下的目录中,然后可以在任何复合键模型的顶部添加一个简单的单线:
class MyModel extends Eloquent { use TraitsHasCompositePrimaryKey; // *** THIS!!! *** protected $primaryKey = array('key1', 'key2'); ...
由jessedp补充:
在我想使用Model :: find之前,这对我一直很有效,因此以下是一些可以添加到上述hasCompositePrimaryKey特性中的代码(可能会更好):
protected static function find($id, $columns = ['*']){ $me = new self; $query = $me->newQuery(); $i=0; foreach ($me->getKeyName() as $key) { $query->where($key, '=', $id[$i]); $i++; } return $query->first($columns);}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)