Laravel - 软删除未生效
Laravel - Soft delete isn't taking effect
我遇到了软删除问题。我的应用程序中有一项功能,用户可以在其中为关注的 属性 广告加注星标。他们还可以取消 属性 广告的星标。
这很好用。当他们取消它时,记录被软删除。 delete_at 时间戳已更新。
但是,如果用户再次尝试给它加注星标,我会收到一条消息说 属性 已经 liked/starred。所以软删除被忽略了?有什么想法吗?
星标属性模型
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class StarredProperty extends Model
{
use SoftDeletes;
protected $fillable = ['property_id', 'user_id'];
public function scopeStarredProperty($query, $propertyId, $userId)
{
return $query->where('property_id', $propertyId)->where('user_id', $userId)->first();
}
}
StarredPropertyController
class StarredPropertyController extends Controller
{
public function star(Property $property, User $user, Request $request)
{
if(!$user->starredProperties()->starredProperty($property->id, $user->id))
{
return response()->json(StarredProperty::create(['property_id' => $property->id, 'user_id' => $user->id]));
}
return response()->json('You have already like this property');
}
public function unstar(Property $property, User $user, Request $request)
{
$starredProperty = $user->starredProperties()->starredProperty($property->id, $user->id);
if($starredProperty->exists())
{
$starredProperty->delete();
}
}
}
您在 if 末尾缺少一个 ->get()
,用于检查 starredProperty 是否存在于 star 函数中。
$user->starredProperties()->starredProperty($property->id, $user->id)
returns 查询,不是记录。要获取记录还需要执行get
,如果没有记录则get
返回的值会是null
.
我遇到了软删除问题。我的应用程序中有一项功能,用户可以在其中为关注的 属性 广告加注星标。他们还可以取消 属性 广告的星标。
这很好用。当他们取消它时,记录被软删除。 delete_at 时间戳已更新。
但是,如果用户再次尝试给它加注星标,我会收到一条消息说 属性 已经 liked/starred。所以软删除被忽略了?有什么想法吗?
星标属性模型
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class StarredProperty extends Model
{
use SoftDeletes;
protected $fillable = ['property_id', 'user_id'];
public function scopeStarredProperty($query, $propertyId, $userId)
{
return $query->where('property_id', $propertyId)->where('user_id', $userId)->first();
}
}
StarredPropertyController
class StarredPropertyController extends Controller
{
public function star(Property $property, User $user, Request $request)
{
if(!$user->starredProperties()->starredProperty($property->id, $user->id))
{
return response()->json(StarredProperty::create(['property_id' => $property->id, 'user_id' => $user->id]));
}
return response()->json('You have already like this property');
}
public function unstar(Property $property, User $user, Request $request)
{
$starredProperty = $user->starredProperties()->starredProperty($property->id, $user->id);
if($starredProperty->exists())
{
$starredProperty->delete();
}
}
}
您在 if 末尾缺少一个 ->get()
,用于检查 starredProperty 是否存在于 star 函数中。
$user->starredProperties()->starredProperty($property->id, $user->id)
returns 查询,不是记录。要获取记录还需要执行get
,如果没有记录则get
返回的值会是null
.