Метод Laravel save () возвращает true, но не обновляет записи

Я использую Eloquent для обновления моей возможности таблицы,

Модель Возможность

<?php namespace App;

use IlluminateDatabaseEloquentModel;

class Opportunity extends Model {

protected $primaryKey = 'OpportunityID';

protected $table = 'opportunitys';
// relationships
public function csfs()
{
    return $this->hasMany('AppCsf', 'opportunityID');
}

public function benefits()
{
    return $this->hasMany('AppBenefit', 'opportunityID');
}

public function risks()
{
    return $this->hasMany('AppRisk', 'opportunityID');
}

public function projects()
{
    return $this->belongsTo('AppProject', 'projectID');
}

public static function createNewOpportunity($input, $projectID)
{
    $opportunity = new Opportunity;
    $opportunity->value = $input['value'];
    $opportunity->margin = $input['margin'];
    $opportunity->duration = $input['duration'];
    $opportunity->tender_type = $input['tender_type'];
    $opportunity->likelihood_of_success = $input['likelihood_of_success'];
    $opportunity->scope_of_work = $input['scope_of_work'];
    $opportunity->deliverables = $input['deliverables'];
    $opportunity->projectID = $projectID;
    $opportunity->high_level_background = $input['high_level_background'];
    if($opportunity->save())
        {
            Opportunity::leadSalesOppComplete($projectID);
            return true;
        };

}

public static function leadSalesOppComplete($projectID)
{
    $task = Lead::where('projectID', '=', $projectID)->first();
    $task->sales_opp = true;
    return $task->save();
}

}

public function updateOpportunity(Request $request, $id) {

Я получаю id и найти возможность.

$something = Opportunity::find($id);

Я умер и бросил это, и я получаю это

Opportunity {#259 ▼
 #primaryKey: "OpportunityID"
#table: "opportunitys"
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:12 [▼
"opportunityID" => 11
"value" => 0
"margin" => 0
"tender_type" => ""
"likelihood_of_success" => 0
"high_level_background" => ""
"scope_of_work" => ""
"deliverables" => ""
"duration" => ""
"projectID" => 6
"created_at" => "2015-03-11 17:45:47"
"updated_at" => "2015-03-11 17:45:47"
 ]
  #original: array:12 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}

что верно. Затем я обновляю их с помощью

    $something->margin = $request['margin'];
    $something->duration = $request['duration'];
    $something->tender_type = $request['tender_type'];
    $something->likelihood_of_success = $request['likelihood_of_success'];
    $something->scope_of_work = $request['scope_of_work'];
    $something->deliverables = $request['deliverables'];
    $something->high_level_background = $request['high_level_background'];

теперь, если я умру и сброшу, я получу

Opportunity {#259 ▼
#primaryKey: "OpportunityID"
#table: "opportunitys"
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:12 [▼
"opportunityID" => 11
"value" => "25000"
"margin" => "0"
"tender_type" => "Proposal"
"likelihood_of_success" => "0"
"high_level_background" => ""
"scope_of_work" => ""
"deliverables" => ""
"duration" => ""
"projectID" => 6
"created_at" => "2015-03-11 17:45:47"
"updated_at" => "2015-03-11 17:45:47"
]
#original: array:12 [▼
  "opportunityID" => 11
  "value" => 0
  "margin" => 0
  "tender_type" => ""
  "likelihood_of_success" => 0
  "high_level_background" => ""
  "scope_of_work" => ""
  "deliverables" => ""
  "duration" => ""
  "projectID" => 6
  "created_at" => "2015-03-11 17:45:47"
  "updated_at" => "2015-03-11 17:45:47"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}

Я только изменил значение, которое показывает изменение.

теперь я бегу

$something->save();

он возвращает true, когда я умираю и сбрасываю его.

но никакие записи не изменяются в базе данных.

какие идеи?

два изображения от tinker

Using Tinker to update

Using Tinker to update part 2

Var_dump after save

3 ответов


эта строка в модели возможностей исправила проблему.

Protected $primaryKey = "opportunityID";

хотя трудно понять, почему все еще можно было получить данные и создать новую запись.


у меня была очень похожая проблема и этот пост привести меня к решению. Я тоже перекрывалprimaryKey.

среда:

SELECT и INSERT операции работы с ,, UPDATE операции не работали, хотя save() вернулся true.

после нахождения этого поста я изменил случай. protected $primaryKey = 'user_id';, Whammy, все три операции работают! Хотел бы я иметь более основательное объяснение, почему это работает. Когда я создал таблицу, я явно использовал upper USER_ID VARCHAR2(50 BYTE) NOT NULL.


у меня была такая же проблема с что Laravel 5.4 и MySQL. Мой первоначальный код был:

$attach = new Attachments ;
$attach->site_id = ($type == 'site' ? $typeId : null) ;
...

путем добавления нулевого первичного идентификатора,save() ведет себя так, как ожидалось.

$attach = new Attachments ;
$attach->id = null ;
$attach->site_id = ($type == 'site' ? $typeId : null) ;
...