【问题标题】:many to many and one to many relationship in EloquentEloquent 中的多对多和一对多关系
【发布时间】:2021-10-09 15:44:34
【问题描述】:

我有三个表:“信使”通过一对多关系与“响应”连接(1 个信使可以有多个响应),以及“结构”通过多对多关系与“信使”连接关系 我想找到连接到某个结构并且在表“响应”中没有响应的信使。 例如,对于在“结构”中标识为 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 不存在。

【问题讨论】:

    标签: laravel eloquent laravel-8


    【解决方案1】:

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

    如果要在关系上使用查询构建器,则需要将其用作方法:$model-&gt;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'));
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 2019-06-13
      • 2017-04-20
      • 2019-03-26
      • 2021-04-21
      • 2013-05-15
      • 2014-09-27
      相关资源
      最近更新 更多