AdvertiseController.php
class AdvertiseController extends Controller
{
...
public function NewAdvertiser()
{
$advertiser = new Advertiser((string)Uuid::generate(4));
$advertiser->createAdvertiser();
return Redirect::route('dashboard');
}
...
}
Advertiser.php
class Advertiser extends Model
{
...
protected $fillable = ['token'];
private $token;
function __construct($token)
{
$this->token = $token;
}
function createAdvertiser()
{
//dd($this);
$this->save();
//dd($this);
}
...
}
第一个dd($this)
打印以下内容:
Advertiser {#181 ▼
#fillable: array:1 [▼
0 => "token"
]
-token: "44f1e74b-ad19-4e73-ac2e-b37ffde59e99"
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: []
#original: []
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: false
+wasRecentlyCreated: false
}
第二个dd($this)
:
Advertiser {#181 ▼
#fillable: array:1 [▼
0 => "token"
]
-token: "295764d5-c45c-4aa9-8ce2-8ed772687fb8"
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:3 [▼
"updated_at" => "2016-05-19 11:39:42"
"created_at" => "2016-05-19 11:39:42"
"id" => 7
]
#original: array:3 [▼
"updated_at" => "2016-05-19 11:39:42"
"created_at" => "2016-05-19 11:39:42"
"id" => 7
]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: true
}
token
有一个减号,它与它有什么关系吗?我找不到任何有关它的信息。
该字段的数据库迁移:
$table->uuid('token');
问题是所有记录都已成功存储,但token
字段为空。
答案 0 :(得分:0)
您的模型存在一些问题。您只需要填充可填充属性。删除构造函数,因为它删除了正确填充模型的雄辩能力,这会导致问题。也不需要包装save方法。同时使令牌成为类的属性不是使其成为模型属性的方法。要回答关于-
符号的问题,那是因为它被声明为私有财产。
这是模型外观的一个示例。
class Advertiser extends Model
{
protected $fillable = ['token'];
}
如果你真的必须覆盖构造函数,你应该确保它用一组属性构造父类。
class Advertiser extends Model
{
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// Your code here
}
}
在这种情况下,你的控制器需要看起来如下所示。
class AdvertiseController extends Controller
{
public function NewAdvertiser()
{
// Create the model with an attributes array
$advertiser = new Advertiser([
'token' => (string)Uuid::generate(4)
]);
// Save the model
$advertiser->save();
return Redirect::route('dashboard');
}
}