【问题标题】:Elloquent ORM Model::with() returning NULL雄辩的 ORM 模型::with() 返回 NULL
【发布时间】:2018-01-14 14:29:19
【问题描述】:

我在使用 Model 对象的 ->with() 方法检索对象时遇到问题。

在我的应用程序中,我有 4 个表格(我在这里写下我认为是表格的基本字段,所以):

**Categories**:
id

**Subcategorie**
id
id_categorie

**UserSubcategorie**
id_user
id_subcategorie

**Lawyers**
user_id

我正在尝试获取给定类别的所有用户(这意味着所有用户都连接到所有类别的子类别)

我的要求如下:

$categorie = LegalCategory::whereIn('id', $arrayCat)->with('legal_subcategories')->get();
foreach ($categorie as $k =>$cat){
    $selectedCat[$k]['categorie'] = $cat;
    $selectedCat[$k]['lawyers'] = 
        Lawyer::Join('lawyers_legal_subcategories', 'lawyers.user_id', '=', 'lawyers_legal_subcategories.user_id')
        ->with('lawyer_subcategories')
        ->whereIn('lawyers_legal_subcategories.legal_subcategory_id', $cat->legal_subcategories)
        ->get();                                                            
}

我得到了正确的律师,但是当我查看 lawyer->legal_subcategories 时,我有 NULL

我不明白为什么,因为当我尝试这个时:

Lawyer::orderBy('created_at')->take(4)->with('lawyer_subcategories')->get()

我在 Lawyer 对象中有我的子类别。

有人知道问题可能是什么吗?

【问题讨论】:

    标签: php laravel model eloquent inner-join


    【解决方案1】:

    问题出在这一行:

    ->whereIn('lawyers_legal_subcategories.legal_subcategory_id', $cat->legal_subcategories)
    

    您需要传递 ID 数组而不是所有子类别!

    $categorie = LegalCategory::whereIn('id', $arrayCat)
                                ->with('legal_subcategories')
                                ->get();
    foreach ($categorie as $k =>$cat){
        $selectedCat[$k]['categorie'] = $cat;
        $selectedCat[$k]['lawyers'] = 
            Lawyer::Join('lawyers_legal_subcategories', 'lawyers.user_id', '=', 'lawyers_legal_subcategories.user_id')
            ->with('lawyer_subcategories')
            ->whereIn('lawyers_legal_subcategories.legal_subcategory_id', 
                        $cat->legal_subcategories->pluck('id'))
            ->get();                                                            
    }
    

    【讨论】:

    • 我还有一些子类别没有被检索到,但其中大部分是。所以我猜你解决了这个问题,我还有另一个问题要找^^但是非常感谢。它大部分工作正常!
    【解决方案2】:

    您应该学习如何使用has many throughEager Loading。这将使您的生活更轻松。

    在您的情况下,您进行了大量查询,从长远来看,这将使您的数据库受到影响。 Eager loading 和 Laravel eloquent 提供了一个非常有效的功能来处理这些情况。

    如果您正确定义了模型,您可以使用 with() 方法检索所有需要的数据。

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 2020-02-18
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2013-04-10
      • 2017-07-29
      相关资源
      最近更新 更多