【问题标题】:laravel Where on nested withlaravel 在哪里嵌套
【发布时间】:2019-10-20 15:39:22
【问题描述】:

我想与他所有没有 etat="archiver" 的人员一起获取位置

分身

class Disponibilite extends Model
{
    public function etat()
    {
        return $this->belongsTo('App\Etat');
    }
}

位置

class location extends Model
{
    public function disponibilite()
    {
        return $this->hasMany('App\Disponibilite');
    }
}

etat 为空

class Etat extends Model
{
}

这是我的尝试

$location = location::where("id", $id)
->with([
    "locataire",
    "prix",
    "acceptations",
    "distances",
    "equipements",
    "logement",
    "language",
    "photo",
    "disponibilite" => function ($query) {
        $query->with(["etat" => function ($q) {
            $q->where("type", "!=", "archiver");
        }]);
    }
])
->first();

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:
    $location = location::with([
        "locataire",
        "prix",
        "acceptations",
        "distances",
        "equipements",
        "logement",
        "language",
        "photo",
        "disponibilite" => function ($disponibilite) {
            // only get the 'disponibilites' that has the following relationship
            $disponibilite->whereHas("etat", function ($etat) {
                $etat->where("type", "!=", "archiver");
            })
            // eager load the relationship
            ->with(["etat" => function ($etat) {
                $etat->where("type", "!=", "archiver");
            }]);
        }
    ])
    // This is the same as using where('id', $id)->first()
    ->find($id);
    

    【讨论】:

    • 我想保留位置,但是 disponibilite 取决于 etat 的类型,Tnx
    【解决方案2】:

    我修复了它,问题是某些行的 disponibilites 有一个 etat (NULL) 所以如果我在回调函数中测试了 etat (null) 的类型,什么都不会发生所以我添加 OrWhere("etat_id",null) 并用 wherehas 更改了 with

    $location = location::with(
                    [
                        "locataire",
                        "prix",
                        "acceptations",
                        "distances",
                        "equipements",
                        "logement",
                        "language",
                        "photo",
                        "disponibilite" => function ($query) {
    
                            $query->whereHas("etat", function ($q) {
    
                                $q->where("type", "!=", "archiver");
                            })->Orwhere("etat_id", null);
                        }
                    ]
                )
                    ->find($id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多