我有一个应用程序模型,它使用了一个特性。我需要这个特性来接收一些数据并在访问器函数中使用它。
内容模型:
use App\Traits\ArchiveTrait;
class Content extends Model
{
use ArchiveTrait;
protected $fillable = ['title','details'];
protected $table = 'contents';
public function getFileName($file_name)
{
return $this->archiving->url.'/media/contents/'.$file_name;
}
}档案特性
trait ArchiveTrait {
private $app_id;
private $archiving;
public function __construct()
{
$this->app_id = config('archiving.id');
$this->archiving = Application::findOrFail($this->app_id);
}
public function guzzleClient() {
$headers = [
'Content-Type' => 'application/json',
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . $this->archiving->token,
];
$client = new \GuzzleHttp\Client([
'headers' => $headers,
'http_errors' => false
]);
return $client;
}
}然后问题是,当我尝试插入一个新的内容时,我会得到'Field‘标题,'details’没有默认值‘SQL错误,但是如果我从模型中删除'use ArchiveTrait’和getFileName函数,那么它就可以正常工作了。我觉得这个特征有点不对劲。
发布于 2020-08-06 14:31:04
Laravel雄辩的模型通过构造函数传递它们的属性。因为您正在重写构造函数,并且没有将任何内容传递给父构造函数,所以您的模型的属性永远不会设置。
您不应该在特征中添加构造函数,但是如果确实需要,可以通过将$attributes变量传递给父构造函数来修复这个问题:
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->app_id = config('archiving.id');
$this->archiving = Application::findOrFail($this->app_id);
}https://stackoverflow.com/questions/63285740
复制相似问题