laravel - Laravel 模型关系也会自动获取所有其他模型关系
问题描述
我希望有人能帮助我。
我有 3 个模型,例如用户、任务和子任务。这些已经通过 hasOne 或 hasMany 链接。一切正常。现在我通过Task::where(..)->with(['user','subtask'])...调用数据,得到相应的结果。
问题是 Subtask 有对 User 的引用,我在使用任务模型时没有得到查询到的用户信息。
如果我使用子任务模型,我会得到用户信息。
如何设置对查询模型的所有引用也同时从数据库中查询?
解决方案
要一次返回更多关系数据,您可以使用以下机制:
$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);
推荐阅读
- php - 如何将 CURLOPT_POSTFIELDS 用于带大括号的查询字符串?- PHP
- c# - 有没有办法将组合框选择写入由 tableLayoutPanel 读取然后显示的文本文件?
- mysql - 如何根据用户从下拉列表中选择的项目加载行轴
- vue.js - vite配置文件根本不生效
- reactjs - 一起使用reactjs和spring boot时的spring boot刷新问题
- c++ - 在 C++ 中以 gedit 的形式关闭程序中的文件
- django - 将动态选择列表传递给基于类的视图中的视图
- javascript - Javascript中的下拉菜单
- javascript - 无法在 Netflix 搜索栏上捕获点击事件
- ios - Flutter:一些表情符号在 iOS 上显示不正确