ActiveRecord.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Author: NODELOG
  5. * DateTime: 2017/8/4 14:33
  6. * Description:
  7. */
  8. namespace common\components;
  9. use Yii;
  10. USE yii\helpers\ArrayHelper;
  11. use yii\base\InvalidConfigException;
  12. class ActiveRecord extends \yii\db\ActiveRecord
  13. {
  14. public function transactions()
  15. {
  16. return [
  17. self::SCENARIO_DEFAULT => self::OP_ALL
  18. ];
  19. }
  20. /**
  21. * @return ActiveQuery
  22. */
  23. public static function find()
  24. {
  25. return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
  26. }
  27. /**
  28. * @param $condition
  29. * @return static|array|null
  30. */
  31. public static function findOneOrFail($condition)
  32. {
  33. return static::findByCondition($condition)->oneOrFail();
  34. }
  35. protected static function findByCondition($condition)
  36. {
  37. $query = static::find();
  38. if (!ArrayHelper::isAssociative($condition)) {
  39. // query by primary key
  40. $primaryKey = static::primaryKey();
  41. if (isset($primaryKey[0])) {
  42. $pk = $primaryKey[0];
  43. if (!empty($query->join) || !empty($query->joinWith)) {
  44. $pk = static::tableName() . '.' . $pk;
  45. }
  46. $condition = [$pk => $condition];
  47. } else {
  48. throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
  49. }
  50. }
  51. return $query->andWhere($condition);
  52. }
  53. }