【问题标题】:Laravel Eloquent belongsToMany()->getResults() ignores soft deletesLaravel Eloquent belongsToMany()->getResults() 忽略软删除
【发布时间】:2015-03-04 07:16:31
【问题描述】:

使用 Laravel 4.2.*,我有一个实现软删除的数据透视表。当我运行 Model::all() 时,我得到了预期的结果,但是当我通过父级访问数据时,我也得到了已删除的行。

父模型分类代码如下:

 public function organizations(){
    return $this->belongsToMany('Organization', 'organization_classifications', 'classification_id', 'organization_id')->getResults();
}

枢轴模型组织分类如下所示:

use Illuminate\Database\Eloquent\SoftDeletingTrait;
class OrganizationClassification extends BaseCrudModel{
    use SoftDeletingTrait;
    protected $dates = ['deleted_at'];
    protected $table = 'organization_classifications'; 
}

该表有一个可为空的列 deleted_at,并且 2 条记录之一在该列中具有正确的日期时间值。

如果我执行 OrganizationClassification::all() 我会返回一行,但如果我执行以下操作:

$c = Classification::find(1);
$ret = $c->rganizations();

我得到了 2 行。

有没有办法只取回未删除的行,但采用 getResults 提供的混合格式?

【问题讨论】:

  • 我猜BaseCrudModel 扩展了Eloquent。还有getResults() 做了什么,因为它不是查询构建器 API 的一部分?
  • API 文档对 getResults() 返回的内容只字未提“获取关系的结果”。它是一个混合数组,并拉动行、枢轴以及可能(我不记得)关联的行。是的,BaseCrudModel 扩展了 Eloquent。

标签: laravel-4


【解决方案1】:

由于软删除列在数据透视表上,您应该尝试为此设置一个条件:

public function organizations()
{
    return $this->belongsToMany('Organization', 'organization_classifications', 'classification_id', 'organization_id')->whereNull('organization_classifications.deleted_at');
}

这将排除deleted_atnull 的条目。

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2014-02-08
    • 2019-02-01
    • 2020-09-08
    • 2016-07-24
    相关资源
    最近更新 更多