Why soft deleted entities appear in query results?

前端 未结 6 771
独厮守ぢ
独厮守ぢ 2020-12-30 20:06

I am trying to implement soft deleting concept.

Here is my object:

class Post extends Eloquent {

    /**
     * The database table used by the model         


        
6条回答
  •  臣服心动
    2020-12-30 20:15

    There is a little trick using soft delete tables and queries in laravel:

    When we create something like

    $objCars = Car::where("color","blue");
    

    The system executes something like that:

    SELECT
      *
    FROM
      cars
    WHERE
      deleted_at IS NULL
    AND
      "color" = 'blue'
    

    So far, so good. But, when we apply the "orWhere" method, something funny happens

    $objCars = Car::where("color","blue")->orWhere("color","red");
    

    The system will execute something like that:

    SELECT 
      * 
    FROM
      cars
    WHERE
      deleted_at IS NULL 
    AND 
      "color" = 'blue'
    OR
      "color" = 'red'
    

    This new query will return all the car where deleted_at is null and the color is blue OR if the color is red, even if the deleted_at is not null. It is the same behavior of this other query, what show the problem more explicitly:

    SELECT 
      * 
    FROM
      cars
    WHERE
      (
        deleted_at IS NULL 
      AND 
        "color" = 'blue'
      )
    OR
      "color" = 'red'
    

    To escape from this problem, you should change the "where" method passing a Closure. Like that:

    $objCars = Car::where(
      function ( $query ) {
        $query->where("color","blue");
        $query->orWhere("color","red");
      }
    );
    

    Then, the system will execute something like that:

    SELECT
      *
    FROM
      cars
    WHERE
      deleted_at IS NULL
    AND
      (
        "color" = 'blue' 
      OR
        "color" = 'red'
      )
    

    This last query, searches for all cars where deleted_at is null and where the color can be or red or blue, as we was want it to do.

提交回复
热议问题