首页 > 解决方案 > Eloquent 中的多对多和一对多关系

问题描述

我有三个表:“信使”通过一对多关系与“响应”连接(1 个信使可能有很多响应),以及通过多对多关系与“信使”连接的“结构”我想要在“reponses”表中查找连接到某个结构并且没有响应的信使。例如,对于在“结构”中标识为 1 的结构“DMO”,我希望找到属于该结构且未出现在“响应”中的信使。我正在使用 Laravel 8,我想用 Eloquent ORM 做到这一点。我正在尝试这个

           public function dmoDG()
           {   
            $structure = Structure::find(1);
            $cou = $structure->courriers;
            
            $courr = $cou->where('repondre','=',1)- 
             >where('dmo_sec','<>',NULL);

            $courriers = $courr->doesntHave('reponses')->get();
           
            return view("DG\dmoDG", compact('courriers'));
           }

方法 Illuminate\Database\Eloquent\Collection::doesntHave 不存在。

标签: laraveleloquentlaravel-8

解决方案


当您使用$model->relation时,它会获取所有相关记录并将它们作为集合返回。

如果要在关系上使用查询构建器,则需要将其用作方法:$model->relation()

因此,如果您将关系作为属性访问,您将获得 Collection。但是,如果您将关系作为一种方法访问,您将获得查询构建器并在其上添加您的 where 子句。

在你的例子中;

public function dmoDG()
{
    $structure = Structure::find(1);
    // $cou = $structure->courriers; // for using without parentheses you got a collection, not a query builder

    $cou = $structure->courriers(); // now you will have a query builder and Where clauses will work on this

    $courr = $cou->where('repondre', '=', 1)->where('dmo_sec', '<>', NULL);

    $courriers = $courr->doesntHave('reponses')->get();

    return view("DG\dmoDG", compact('courriers'));
}

实际上,您可以将它们通过管道连接到一个衬里:

public function dmoDG()
{
    $structure = Structure::find(1);
    
    $courriers = $structure->courriers()->where('repondre', '=', 1)->where('dmo_sec', '<>', NULL)->doesntHave('reponses')->get();

    return view("DG\dmoDG", compact('courriers'));
}

确保正确指定您的关系和列名。


推荐阅读