Laravel更新方法未按预期工作

时间:2016-07-14 08:26:22

标签: database laravel model-view-controller laravel-5 eloquent

我正在使用以下代码更新记录的两个字段:

$companyPlan = CompanyPlan::whereCompanyId($companyId)->first();
$companyPlan->update(['plan_id' => $planId, 'next_plan_id' => $planId])

它的作用是更新plan_id字段,但不更新next_plan_id

plan_idnext_plan_id都在模型的$ fillable数组中。

这确实是一种奇怪的行为,但我不知道为什么会这样。

protected $fillable = ['plan_id', 'next_plan_id'];
protected $hidden = [];

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

CompanyPlan::where('company_id', $companyId)->first()
    ->update(['plan_id' => $planId, 'next_plan_id' => $planId]);

答案 1 :(得分:0)

您是否尝试过此操作,例如 Kjell 在评论中说:

$companyPlan->plan_id = $planId;
$companyPlan->next_plan_id = $planId;
$companyPlan->save();

答案 2 :(得分:0)

这种行为是因为你的表没有任何主键,所以雄辩不能正确更新它(因为它使用主键来更新单个模型实例)。

您应该按其唯一属性选择行,并在同一查询中更新它,如下所示:

    'read and validate inventory text file
    Dim invntFile As StreamReader
    If File.Exists("inventory.txt") Then
        invntFile = File.OpenText("inventory.txt")
        Dim indexInvnt As Integer = 0
        While Not invntFile.EndOfStream
            Dim entirelineInvnt = invntFile.ReadLine
            Dim inventory() As String = entirelineInvnt.Split(","c)
            Dim itemName As String = inventory(0)
            Dim itemPrice As Double = CDbl(inventory(1))
            Dim itemBulkAmt As Double = CDbl(inventory(2))
            Dim itemBulkPrice As Double = CDbl(inventory(3))
            itemLabel(indexInvnt) = itemName
            priceReg(indexInvnt) = itemPrice
            amtBulk(indexInvnt) = itemBulkAmt
            priceBulk(indexInvnt) = itemBulkPrice
            indexInvnt += 1
        end while
     end if

通过删除first()方法,您只在一个查询中完成工作:

CompanyPlan::where('company_id', $companyId)
    ->update(['plan_id' => $planId, 'next_plan_id' => $planId]);