我遇到的问题是我想保存模型,但我有一个写入实例的方法调用,并且出于某种原因 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]:未找到列:1054“字段列表”中的未知列“currentCampaign”(SQL:更新
clubsset
updated_at= 2014-07-08 12:49:17,
currentCampaign= 27,其中
id= 23)
考虑到 currentCampaign
不在 $fillable
数组中,我不知道发生了什么。我是否误解了它的工作原理?
谢谢
编辑:为了清楚起见,$club
中加载了一些不同的内容,而不仅仅是广告系列。我只是出于说明目的给出一个。
请您参考如下方法:
您在模型对象上保存的任何不是属性的内容都将被视为属性/表列。为了避免这种情况,您可以简单地在模型上声明这些属性:
// Club model
public $currentCampaign;
那么使用您的代码就不会导致您现在遇到的错误。
无论如何,您可能应该考虑 @watcher 关于处理关系的建议,但这取决于您的应用。
<小时 />关于fillable
数组 - 它与保存数据无关,而是与用数据数组填充对象(批量分配)有关:
$model->fill($someArray);
当您__construct
新对象、保存或更新提供数组等时,会调用此函数。