Lumen5.5 分表时,无法使用 updateOrCreate
我的业务需要分表,这是我的Model
MaterialExtend.php
<?php
/**
* Created by PhpStorm. * User: 13018 * Date: 2019/12/24 * Time: 19:55 */
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class MaterialExtend extends Model
{
protected $connection = 'db_material_center';
protected $table = '';
protected $fillable = ['app_id','material_id','url','type','size','property'];
public function setTable($table){
$this->table = $table;
return $this;
}
}
2,这是我的MaterialExtendRepository.php
<?php
namespace App\Repositories;
use App\Models\MaterialExtend;
use Illuminate\Support\Facades\Input;
class MaterialExtendRepository extends Repository
{
private $table;
private $prefix = 't_material_extend';
private $app_id;
private $materialExtend;
private $fields = ['id','app_id','material_id','url','type','size','state','property'];
public function __construct(){
$app_id = Input::get('app_id');
$this->app_id = $app_id;
$this->table = $this->getTableName($app_id,$this->prefix);
$this->materialExtend = (new MaterialExtend())->setTable($this->table);
}
public function setTable($app_id){
$this->app_id = $app_id;
$this->table = $this->getTableName($app_id,$this->prefix);
$this->materialExtend = (new MaterialExtend())->setTable($this->table);
return $this;
}
public function insert($data){
return $this->materialExtend->insert($data);
}
public function updateOrCreate($where,$data){
return $this->materialExtend->updateOrCreate($where,$data);
}
}
3,然后我controller里面使用了依赖注入,DemoController.php
代码如下
public function updateOrCreate(Request $request,MaterialExtendRepository $materialExtend){
$app_id = $request->input('app_id');
$material_id = $request->input('material_id');
$url = $request->input('url');
$where = [
'app_id' => $app_id,
'material_id' => $material_id
];
$material_extend_info['url'] = $url;
$material_extend_info['size'] = 0;
$material_extend_info['property'] = '';
$material_extend_info['type'] = MaterialTypeEnum::PATCH_IMG;
$materialExtend = $materialExtend->setTable($app_id);
$data = array_merge($where,$material_extend_info);
$table = $this->getTableName($app_id,'t_material_extend');
$result = $materialExtend->insert($data);
$result = $materialExtend->updateOrCreate($where,$material_extend_info);
return ResponseBuilder::instance()->response();
}
能使用insert方法,不能使用updateOrCreate方法,insert时能正确根据app_id分表 后插入数据库,但是updateOrCreate提示表不存在,table为空了,报错信息如下
SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name '' (SQL: insert into ` (
app_id,
material_id,
url,
size,
property,
type,
updated_at,
created_at`) values (appvr5gqdr56848, 1234, abc-3.mp4, 0, , 7, 2020-01-10 11:04:19, 2020-01-10 11:04:19))
推荐文章: