【问题标题】:After override table name create not working覆盖表名后创建不起作用
【发布时间】:2020-01-07 04:51:26
【问题描述】:

__construct 上覆盖表名后,它没有按预期创建。它仅存储唯一的默认值。

控制器:“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
]
.....

它只是添加了默认值,我必须尝试获取异常,但它没有异常。

【问题讨论】:

  • 你有 new_test_me 表吗?
  • 是的,我有 new_test_me 表。
  • 所以它将插入new_test_me表而不会出错
  • 是的,但是像 id、updated_at、created_at 这样的默认值不是我必须在 create() 上添加为数据的值
  • 不,您不需要这样做,id 是您创建对象时的自动增量主键。它会增加,created_atupdated_at 会自动设置为 current_time。

标签: php laravel eloquent laravel-5.6


【解决方案1】:

只需要在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"
]
.....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2014-04-03
    • 1970-01-01
    • 2020-02-02
    • 2016-08-22
    • 2015-03-16
    • 1970-01-01
    相关资源
    最近更新 更多