Laravel Eloquent ORM - save()返回未找到的列(MySQL错误)

Jos*_*oth 2 php orm model eloquent laravel-4

我遇到的问题是我想保存模型,但我有一个方法调用写入实例,由于某种原因,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;
    } 
}
Run Code Online (Sandbox Code Playgroud)

问题存在于"俱乐部设置"页面上,用户可以在其中编辑一些内容 - 我有一些在不同表上运行的更新,然后我会使用$club->save().我发现即使我之后直接调用它getCurrentCampaign,它也会抛出错误.

    $club = Club::findOrFail($clubID);
    $club->getCurrentCampaign();
    $club->save(); // Error
Run Code Online (Sandbox Code Playgroud)

错误信息: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'currentCampaign' in 'field list' (SQL: update俱乐部set的updated_at = 2014-07-08 12:49:17,currentCampaign = 27 whereID= 23)

考虑到currentCampaign不在$fillable阵列中,我不知道发生了什么.我误解了它是如何工作的吗?

谢谢

编辑:为清楚起见,加载了一些不同的内容$club,而不仅仅是广告系列.我只是为了说明目的而给出一个.

Jar*_*zyk 5

您在Model对象上保存的非属性的任何内容都将被视为属性/表列.为避免这种情况,您只需在模型上声明这些属性:

// Club model
public $currentCampaign;
Run Code Online (Sandbox Code Playgroud)

然后使用您的代码不会导致您现在遇到的错误.

无论如何,可能你应该考虑@ watcher关于使用关系的建议,但这取决于你的应用程序.


关于fillable数组 - 它与保存数据无关,而是与填充对象和数据数组(质量分配):

$model->fill($someArray);
Run Code Online (Sandbox Code Playgroud)

这是在__construct新对象调用时,保存或更新提供数组等.