我尝试通过以下代码将我的对象保存在数据库中:
$preview = new ProjectProductPreview();
$preview->user_id = $user_id;
$preview->path = $preview_url;
$preview->type = $type;
$preview->project_product_id = $product_id;
$preview->save();
我遇到了奇怪的错误。当调用 save() 方法时会出现此错误。 我检查了我的laravel日志,有这个错误。我可以精确地调试它,因为在这种情况下,错误堆栈只有两个位置
[2015-02-17 09:37:30] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function getKey() on a non-object' in /var/www/erp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php:133
Stack trace:
#0 [internal function]: Illuminate\Exception\Handler->handleShutdown()
#1 {main} [] []
我的模型看起来像:
class ProjectProductPreview extends BaseModel {
protected $table = 'project_products_preview';
public function user() {
return $this->belongsTo('User');
}
public function project_product() {
return $this->belongsTo('ProjectProduct', 'project_product_id');
}
public function projectProduct()
{
return $this->belongsTo('ProjectProduct', 'project_product_id');
}
public function message() {
return $this->belongsToMany('Message');
}
public function getThumb() {
$path = $this->path;
$thumb_path = str_replace('.jpg', '_70.jpg', $path);
return $thumb_path;
}
public function fullPath() {
return public_path($this->path);
}
public function getPath()
{
return $this->path;
}
public function getUrlAttribute() {
$product_id = $this->project_product_id;
return '/product/' . $product_id . '#' . $this->id;
}
public function isAccepted()
{
if($this->accepted==1){
return true;
}
return false;
}
public function accept()
{
ProjectProductPreview::where('project_product_id',$this->project_product_id)->update(array('accepted'=>0));
$this->accepted=1;
$this->save();
Event::fire('project_product_preview.accepted', array($this));
}
public function acceptRemove()
{
$this->accepted=0;
$this->save();
Event::fire('project_product_preview.remove_accept', array($this));
}
}
我对此不太确定,但我认为这条线
$preview->project_product_id = $product_id;
导致了这个问题。您与
ProjectProduct
有关系,因此您可能想做某事。实际上就像这样:
$preview->projectProduct()->associate(ProjectProduct::find($product_id));
请参阅 有关插入模型的 laravel 文档。另请注意,您与
ProjectProduct
有两个相同的关系,这也可能会导致意外行为。至少有一个是多余的。
// one can be removed
//public function project_product() {
// return $this->belongsTo('ProjectProduct', 'project_product_id');
//}
public function projectProduct()
{
return $this->belongsTo('ProjectProduct', 'project_product_id');
}