排行榜

Yii动态AR模型

本文阅读 1 分钟
首页 后端开发 正文
广告

业务中有时候有这种情况出现,有些数据表是动态生成的,这时候如果有一个动态AR可以使用,这真是极好的。在网上搜了一圈,只有github上yii2的issue里,有人提供了一些思路,我就沿着这个思路进行了一些完善,代码如下:

<?php
namespace app\models;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
class Mar extends ActiveRecord{
public static $table = '';
/**
* Mar constructor.
* @param array $table
* @param array $config
*/
public function __construct($table, $config = [])
{
self::$table = $table;
parent::__construct($config);
}
/**
* @return array|string
*/
public static function tableName()
{
return self::$table;
}
// public function rules()// {// return [// ];// }//// public function attributeLabels()// {// return [// ];// }
/**
* @param $table
* @return object
* @throws InvalidConfigException
*/
public static function findx($table)
{
if (self::$table != $table) {
self::$table = $table;
}
return Yii::createObject(ActiveQuery::className(), [get_called_class(), ['from' => [static::tableName()]]]);
}
/**
* @param array $row
* @return static
*/
public static function instantiate($row)
{
return new static(static::tableName());
}
/**
* @param $table
* @param $condition
* @return mixed
* @throws InvalidConfigException
*/
public static function findOnex($table, $condition)
{
return static::findByConditionx($table, $condition)->one();
}
/**
* @param $table
* @param $condition
* @return mixed
* @throws InvalidConfigException
*/
public static function findAllx($table, $condition)
{
return static::findByConditionx($table, $condition)->all();
}
/**
* @param $table
* @param $condition
* @return mixed
* @throws InvalidConfigException
*/
protected static function findByConditionx($table, $condition)
{
$query = static::findx($table);
if (!ArrayHelper::isAssociative($condition)) {
// query by primary key
$primaryKey = static::primaryKey();
if (isset($primaryKey[0])) {
$condition = [$primaryKey[0] => $condition];
} else {
throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
}
}
return $query->andWhere($condition);
}
}

其中,rules()方法、attributeLabels()方法、search()方法我没有去实现,这块可以动态实现,需要看情况而定。

目前这个完成度,可以实现

$user = new Mar('user');
$user->username = 'xxx';
$user->save()
$user = Mar::findx('user')->where(['id' => 1])->one();
$user = Mar::findOnex('user', 1);

这些基本操作已经都实现了,其中'user'就是动态表名。

暂时我是这么实现的,发出来让大家乐呵乐呵。


本文来自投稿,不代表本站立场,如若转载,请注明出处:https://www.unfit.cn/archives/43.html
composer安装Yii2
« 上一篇 07-19
Yii查看执行的sql
下一篇 » 07-19
广告

相关推荐