Elloquent ORM Model :: with()返回NULL

时间:2017-08-07 10:02:17

标签: php laravel model eloquent inner-join

我在使用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()

我在律师对象中有我的子类别。

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

2 个答案:

答案 0 :(得分: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();                                                            
}

答案 1 :(得分:1)

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

在您的情况下,您正在进行大量查询,这将使您的数据库长期受损。渴望加载和Laravel雄辩提供了一个非常有效的功能来处理这种情况。

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