class Blog extends Model
{
protected $table = 'default_table';
private static $prefix;
public $timestamps = false;
public function __construct( $prefix = '' )
{
self::$prefix = $prefix;
$this->table= self::$prefix . '_blog';
parent::__construct();
}
public function insertOrUpdate($attributes, $prefix = '')
{
$ad = new self($prefix);
return $ad;//这个位置的时候 调用的表名还是带有传进来的前缀的
if (isset($attributes['id']) && $attributes['id']) {
// $ad = DB::table($prefix . '_ad_category')->find($attributes['id']);
$ad = $ad->where(['id'=>$attributes['id']])->first();
dd($ad);//这个时候查的数据是带前缀的表名,但是对象里面的显示的表名发生了变化
return $ad;
}
$ad->title = $attributes['title'];
$ad->begin = $attributes['begin'];
$ad->end = $attributes['end'];
$ad->img = '';
$ad->url = $attributes['url'];
$ad->category_id = $attributes['category_id'];
$ad->operator_id = $attributes['operator_id'];
return $ad->save();//这个位置修改的就是未带前缀的表名了。我想知道怎么才能传进来前缀的时候,这个模型里全部使用的是指定的表,而不是在去调用默认的表
}
}
自问自答吧:
我们知道,要动态改变 Eloquent Model 的表名可以使用 setTable 方法:
但是在 setTable 之后使用 create 插入数据,使用的还是原来的表:
来看看 setTable 的源码:
注意,这里 new 的是 static 关键字。自 PHP 5.3.0 起,PHP 增加了一个叫做后期静态绑定的功能,用于在继承范围内引用静态调用的类。 这里不做详细说明,具体参考:后期静态绑定。
也就是说 create 的时候并没有进行修改表名的操作,而实例化的是你继承了 Model 类的子类的类名。
那么怎么解决呢?
即可!
举例子:
作者:伍源辉
链接:http://www.jianshu.com/p/e119...