【问题标题】:Laravel - Soft delete isn't taking effectLaravel - 软删除没有生效
【发布时间】:2019-09-09 02:34:31
【问题描述】:

我遇到了软删除问题。我的应用中有一个功能,用户可以在其中为关注的房地产广告加注星标。他们还可以取消为房地产广告加星标。

这很好用。当他们取消星号时,该记录被软删除。 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();
        }
    }
}

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-5.8


    【解决方案1】:

    您在 if 末尾缺少一个 ->get(),用于检查 star 函数上是否存在 starredProperty。 $user->starredProperties()->starredProperty($property->id, $user->id) 返回查询,而不是记录。要获取记录还需要执行get,如果没有记录则get返回的值为null

    【讨论】:

    • StarredProperty 是我第一个代码块中模型的查询范围。查询返回 first() 记录。
    • 你不应该首先在范围上这样做,范围应该返回查询构建器实例,检查这个答案:laracasts.com/discuss/channels/laravel/…
    • 非常感谢。所以我不应该先使用或进入范围?
    • 不,范围只是为了形成复杂的查询,一旦你通过在控制器上链接范围形成查询,你可以调用 get 或首先实际执行由所有链接的范围进行的查询.
    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多