首页 > 解决方案 > Laravel 模型关系也会自动获取所有其他模型关系

问题描述

我希望有人能帮助我。

我有 3 个模型,例如用户、任务和子任务。这些已经通过 hasOne 或 hasMany 链接。一切正常。现在我通过Task::where(..)->with(['user','subtask'])...调用数据,得到相应的结果。

问题是 Subtask 有对 User 的引用,我在使用任务模型时没有得到查询到的用户信息。

如果我使用子任务模型,我会得到用户信息。

如何设置对查询模型的所有引用也同时从数据库中查询?

标签: laraveleloquentlaravel-relations

解决方案


要一次返回更多关系数据,您可以使用以下机制:

$Data = $Task::where(...)
    ->with([
        'user'=>function($userQuery){
            // mechanism is recursive; you can extend it to infinity :)
            $userQuery->with([
                            'other', 
                            'relationships', 
                            'here'=>function($hereQuery){ ... } 
                        ]); 
        },

        'subTask',

        'anotherRelationship' => function($anotherRelationship) {
            $anotherRelationship->select('column');
            $anotherRelationship->where('column2', 'whatever');
        }
    ])
    ->get();

// dump data
dd($Data);

我不知道您是否正在寻找这个 - 如果您想在模型实例化后加载一些关系,您可以$with在模型代码中附加一个魔术变量并指定要加载的关系:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable = ['col1', 'col2', 'col3', ...];

    // specify which relationships you want to load automatically
    protected $with = [
        'users',
        'anotherRelationship'=>function($anotherRelationshipQuery){
            $anotherRelationshipQuery->select( ... );
        },
        'andSomeOtherRelationship'

        ...
    ];

    ...
}

现在,您不再需要在检索数据时手动加载关系。它们会自动加载:

$Data = $Tast::where( ... )->get();

dd($Data);


推荐阅读