【问题标题】:Access relation in forelse on the same model - laravel同一模型上的访问关系 - laravel
【发布时间】:2019-07-30 14:23:16
【问题描述】:

我有一个关于在 laravel 模型中访问关系的问题。我有与翻译模型和类别模型相关的类别模型(相同的模型/本身 - 一个类别可以使用数据透视表 CategoryToCategory 显示在其他类别中):

类别型号:

    public function childCategories(){
        return $this->hasManyThrough('App\Models\Category',
            'App\Models\CategoryToCategory',
            'id_parent_category', 
            'id',  
            'id',
            'id_category'); 
    }

    public function translation($locale = null)
    {
        if ($locale == null) {
            $locale = \App::getLocale();
        }
        return $this->hasOne('App\Models\CategoryLanguage', 'id_category', 'id')->where('locale', '=', $locale);
    }

现在我采用当前类别+翻译+子类别:

$category = Category::with('translation', 'childCategories')->active()->where('id', $id)->first();

并显示所有孩子的名字:

@forelse($category->childCategories as $category)
   {{ $category->translation->name }}
@endforelse

我工作每个子类别都会进行另一个查询以获取翻译(它不会为 forelse 中的元素加载)。那么如何在foreaching加载关系的类别模型中加载关系“翻译”?

我可以查询模型 CategoryToCategory 以获取该模型的所有子类别 + 加载翻译,结果相同:

$categories = CategoryToCategory::with('translation')->where('id_parent_category', $id)->get();

并且会有一个翻译查询。我仍然对使用第一个解决方案而不是查询 categoryToCategory 感到好奇。

有什么想法吗?

祝你有美好的一天!

【问题讨论】:

  • 试试看文档:$translation = Category::find($id)->translation; dd($translation);

标签: laravel eloquent eloquent-relationship


【解决方案1】:

要急切加载远距离关系,您可以像这样使用点符号:

$category = Category::with('translation', 'childCategories.translations')
    ->active()
    ->where('id', $id)
    ->first();

这被称为“嵌套急切加载”,并在此处的文档中引用: https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 2016-07-12
    • 2022-01-25
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2014-05-15
    相关资源
    最近更新 更多