如何更新 table Laravel 中的字段或创建?
How to update field in table Laravel or create?
我尝试通过主键 user_id
.
更新 table 中的字段 rate
所以,我需要递增或递减 rate
字段。如果行不存在,我需要创建它。
我试过了:
$this->point = -1; // Or $this->point = 1;
Rating::updateOrCreate(["user_id", $id], ["rate" => $this->point]);
但是不行:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `rating` where (`0` = user_id and `1` = 5) limit 1)
这是因为您将列和值作为两个单独的值传递。
变化:
["user_id", $id]
至:
["user_id" => $id]
希望对您有所帮助!
Laravel (eloquent) 提供了更新相关模型的流畅方式。
假设模型结构如下:
Rating.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function ratings()
{
return $this->hasMany('App\Rating');
}
您可以通过 associate()
轻松更新关系
$user = User::findOrFail($userId);
$rating = Rating::findOrFail($ratingId);
$rating->user()->associate($user)->save();
阅读更多关于 Relationships in Eloquent
我尝试通过主键 user_id
.
rate
所以,我需要递增或递减 rate
字段。如果行不存在,我需要创建它。
我试过了:
$this->point = -1; // Or $this->point = 1;
Rating::updateOrCreate(["user_id", $id], ["rate" => $this->point]);
但是不行:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `rating` where (`0` = user_id and `1` = 5) limit 1)
这是因为您将列和值作为两个单独的值传递。
变化:
["user_id", $id]
至:
["user_id" => $id]
希望对您有所帮助!
Laravel (eloquent) 提供了更新相关模型的流畅方式。
假设模型结构如下:
Rating.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function ratings()
{
return $this->hasMany('App\Rating');
}
您可以通过 associate()
$user = User::findOrFail($userId);
$rating = Rating::findOrFail($ratingId);
$rating->user()->associate($user)->save();
阅读更多关于 Relationships in Eloquent