我遇到的问题是我想保存模型,但我有一个方法调用,写入实例,由于某种原因Laravel试图更新列。
俱乐部模式(相关代码):
use Illuminate'Database'Eloquent'SoftDeletingTrait;
class Club extends Eloquent
{
use SoftDeletingTrait;
protected $table = 'clubs';
protected $fillable = array('name', 'address', 'city', 'state', 'zip', 'contact_name', 'contact_email', 'contact_phone', 'contact_photo', 'club_code', 'logo');
public function getCurrentCampaign($id = 0)
{
if (!$id)
{
if ($this->currentCampaign)
{
return $this->currentCampaign;
}
$id = $this->id;
}
$now = date('Y-m-d H:i:s');
$this->currentCampaign = DB::table('campaigns')
->where('club_id', $id)
->where('start_date', '<=', $now)
->where('end_date', '>=', $now)
->pluck('id');
return $this->currentCampaign;
}
}
这个问题存在于"俱乐部设置"页面上,用户可以编辑一些东西-我有一些更新在不同的表上运行,然后后来我使用$club->save()
。我发现,即使我在getCurrentCampaign
之后直接调用它,它也会抛出错误。
$club = Club::findOrFail($clubID);
$club->getCurrentCampaign();
$club->save(); // Error
错误信息:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'currentCampaign' in 'field list' (SQL: update
clubs set
updated_at = 2014-07-08 12:49:17,
currentCampaign = 27 where
id = 23)
考虑到currentCampaign
不在$fillable
数组中,我不知道发生了什么。我是不是误解了这是怎么回事?
编辑:为了清楚起见,$club
中装载了一些不同的东西,而不仅仅是活动。我只是简单地举一个例子
保存在Model对象上的任何非属性的内容都将被视为属性/表列。为了避免这种情况,您可以简单地在模型上声明这些属性:
// Club model
public $currentCampaign;
那么使用你的代码就不会导致你现在遇到的错误。
无论如何,也许你应该考虑@watcher关于使用关系的建议,但这取决于你的应用。
关于fillable
数组-它与保存数据无关,而是用数据数组填充对象(批量分配):
$model->fill($someArray);
当您__construct
新对象,保存或更新提供数组等时调用
我不认为你是在以' laravel方式'指定你的活动关系。潜在的问题是,您正在向模型添加一个属性,并且,在保存期间,Eloquent认为额外的非标准属性表示数据库中的一列,因此它试图将其保存为这样。
这是我解决它的路径:
public function campaigns()
{
// 'hasMany' may not be what you need, just guessing
// from what I see so far...
return $this->hasMany('Campaigns');
}
public function currentCampaigns($now)
{
return $this->campaigns
->where('start_date', '>', $now)
->where('end_date', '<', $now);
}
现在,给定一个"俱乐部"的实例,你可以像这样获得它的当前活动:
$club->currentCampaigns(date('Y-m-d H:i:s'));
上面的关系取决于您如何在数据库中构建关系。
如果你的俱乐部表有一个'campaign_id'字段,那么俱乐部模型和活动模型的关系将是
belongsTo
。如果有第三个表格,其中包含活动id和俱乐部id,这就是你如何确定俱乐部与活动相关的方式,这种关系是
hasMany
我也相信,如果你有一个campaign_id
在你的俱乐部表,它将需要存在于可填充数组,以便实际能够设置它。