【发布时间】:2018-12-29 03:33:21
【问题描述】:
我有一个正在尝试创建的模型。
Sale::create([
'user_id'=>Auth::user()->id,
'tenant_id'=>Auth::user()->tenant_id,
'price'=>$price
]);
这可以很好地创建记录。除了它所填写的只是 created_at、updated_at 和 id 字段。它忽略了我在这里选择的字段。
即使设置了可填充
$fillable = ['user_id','tenant_id','app_id','price','other_fields etc etc']
这里怎么了??为什么记录只插入这 3 个值而没有其他内容???
如果我只是这样做
$sale = New Sale;
$sale->user_id = Auth::user()->id;
$sale->tenant_id = Auth::user()->tenant_id;
$sale->price = $price;
$sale->save();
它工作得很好,并进入了完整的记录。
现在,我就这样离开它,因为它可以工作....但我想弄清楚为什么 Model::create() 不工作。因为我真的很想保持我的编程一致,因为我使用 Model::create() 基本上在我的应用程序中创建新记录的其他任何地方。
EDIT - 被要求发布销售模型
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Sale extends Model
{
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->connection = env("DB_POOL_1_CONNECTION");
$this->table = "sales";
}
// ******** INPUT VALIDATION ************* //
/**
* The attributes that are mass assignable.
* @var array
*/
protected $fillable =['tenant_id','rep_id''lead_id','invoice_id','total_price','net_price','tax'];
protected $hidden = [];
protected $guarded = [];
我还发布了我的文件模型,它工作正常,并且完全相同
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class UserFile extends Model
{
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->connection = env("DB_POOL_1_CONNECTION");
$this->table = "user_files";
}
// ******** INPUT VALIDATION ************* //
/**
* The attributes that are mass assignable.
* @var array
*/
protected $fillable =['tenant_id','user_id''filename','description','file_size', 'file_path'];
protected $hidden = [];
protected $guarded = [];
只有销售模型不会插入 Model::create()。
UserFile 模型可以。我的其他 28 个模型也是如此,它们都共享完全相同的模板,显然只是不同的表。
【问题讨论】:
-
$fillable是否受到保护?protected $fillable = ['user_id','tenant_id','app_id','price', ...] -
是的,但它在我所有其他型号上都受到保护,而且它们工作得很好。
-
Sale是否有构造函数,如果有,是否调用parent::__construct($attributes);? -
我所有的模型都是相同的副本。他们都有 parent::__construct() 和受保护的 $fillable。所有其他模型都可以工作,但不是这个
-
旁注:您不应该在配置文件之外使用
env('something'),因为在使用php artisan config:cache缓存配置后将不会加载环境文件。相反,创建一个包含环境变量的配置并在您的代码中访问该配置(请参阅模型中的数据库连接)。