我在使用软删除时遇到问题.我的应用程序中有一个功能,用户可以为其添加关注的属性广告.他们还可以取消为房地产广告加注星标.
这很好.当他们取消星标时,记录将被软删除. delete_at时间戳已更新.
但是,如果用户尝试再次对其加注星标,则会收到一条消息,指出该属性已被点赞/加注星标.那么软删除被忽略了吗?有任何想法吗?
StarredPropertyModel
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();
}
}
}
解决方法:
如果在star函数上是否存在starredProperty,则在if末尾缺少-> get().
$user-> starredproperty()-> starredProperty($property-> id,$user-> id)返回查询,而不是记录.要获取记录,您仍然需要执行get,如果没有记录,则get返回的值将为null.