覆盖 table 名称后创建不起作用
After override table name create not working
覆盖 __construct 上的 table 名称后,未按预期创建。它仅存储唯一的默认值。
控制器:"TestMeController"
use App\TestMe;
use Illuminate\Http\Request;
use Log;
class TestMeController extends Controller
{
public function setCreateData() {
config(['app.temp_db' => "new_test_me"]);
$test_me_data = ["data" => "new table data"];
$data = TestMe::create( $test_me_data );
dd($data);
}
}
型号:"TestMe"
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TestMe extends Model
{
protected $table = "test_me";
protected $guarded = ['id'];
protected $connection = "mysql";
public function __construct() {
if( config('app.temp_db') != "") {
$this->table = config('app.temp_db');
}
}
}
输出
.....
#original: array:3 [
"updated_at" => "2020-01-06 13:34:18"
"created_at" => "2020-01-06 13:34:18"
"id" => 100
]
.....
它只添加了默认值,我必须尝试获取异常,但没有异常就可以了。
只需要在 construct
上传递 $attributes
型号:"TestMe"
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TestMe extends Model
{
protected $table = "test_me";
protected $guarded = ['id'];
protected $connection = "mysql";
public function __construct(array $attributes = []) {
parent::__construct($attributes);
if( config('app.temp_db') != "") {
$this->table = config('app.temp_db');
}
}
}
输出
.....
#original: array:3 [
"updated_at" => "2020-01-06 13:34:18"
"created_at" => "2020-01-06 13:34:18"
"id" => 100
"data" => "new table data"
]
.....
覆盖 __construct 上的 table 名称后,未按预期创建。它仅存储唯一的默认值。
控制器:"TestMeController"
use App\TestMe;
use Illuminate\Http\Request;
use Log;
class TestMeController extends Controller
{
public function setCreateData() {
config(['app.temp_db' => "new_test_me"]);
$test_me_data = ["data" => "new table data"];
$data = TestMe::create( $test_me_data );
dd($data);
}
}
型号:"TestMe"
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TestMe extends Model
{
protected $table = "test_me";
protected $guarded = ['id'];
protected $connection = "mysql";
public function __construct() {
if( config('app.temp_db') != "") {
$this->table = config('app.temp_db');
}
}
}
输出
.....
#original: array:3 [
"updated_at" => "2020-01-06 13:34:18"
"created_at" => "2020-01-06 13:34:18"
"id" => 100
]
.....
它只添加了默认值,我必须尝试获取异常,但没有异常就可以了。
只需要在 construct
型号:"TestMe"
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TestMe extends Model
{
protected $table = "test_me";
protected $guarded = ['id'];
protected $connection = "mysql";
public function __construct(array $attributes = []) {
parent::__construct($attributes);
if( config('app.temp_db') != "") {
$this->table = config('app.temp_db');
}
}
}
输出
.....
#original: array:3 [
"updated_at" => "2020-01-06 13:34:18"
"created_at" => "2020-01-06 13:34:18"
"id" => 100
"data" => "new table data"
]
.....