父模型仍返回软删除的子实例

时间:2016-12-28 04:53:37

标签: php laravel-5 orm eloquent soft-delete

我有一个父模型Library,它有很多Books。 Eloquent使定义关系变得如此容易。我使用softdeleting特征在书籍模式上启用了SoftDeletes

问题:

当我删除书籍实例时,书籍实例上的deleted_at属性被设置为当前时间戳(如预期的那样)。

但是当我查询属于Library的所有图书时,结果中包含所有图书,包括已删除的图书。

我只想获取尚未删除的books

class Library extends Model {
   public function books() {
      return $this->hasMany(Book::class);
   }
}

class Book extends Model {
   use SoftDeletes;
   public function library() {
      return $this->belongsTo(Library::class, 'library_id');
   }
}

$softDeleteBook = Book::find(1);
$softDeleteBook->delete();
$books = Library::find(1)->books;
// $books contains even $softDeleteBook
// I do not want to get $softDeleteBook

1 个答案:

答案 0 :(得分:0)

@ Elisha-Wigwe Chijioke。您是否已将$table->softDeletes();添加到迁移文件中。

样本模型就像这样

<?php 
class Video extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    public function category()
    {
        return $this->belongsTo('LearnCast\Category');
    }
 }
?>

查看示例迁移模式构建

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('videos', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
        $table->softDeletes();
    });
}

我希望这会有所帮助