>
<!-- Syntax highlighted by torchlight.dev -->$post->loadMissing(['comments', 'author']); // With constraints $post->loadMissing(['comments' => function($query) { $query->latest()->take(5); }]);当具有可选的不同部分需要不同的关系数据的可选或仪表板时,此功能尤其有价值。
。
<!-- Syntax highlighted by torchlight.dev --><?php namespace App\Http\Controllers; use App\Models\Dashboard; use Illuminate\Http\Request; class DashboardController extends Controller { public function show(Request $request, Dashboard $dashboard) { // Load base relationships $dashboard->loadMissing([ 'widgets', 'owner', ]); // Conditionally load additional data if ($request->section === 'analytics') { $dashboard->loadMissing([ 'widgets.viewHistory' => function($query) { $query->whereBetween('viewed_at', [ now()->subDays(30), now() ]); }, 'widgets.interactions' ]); } if ($request->section === 'sharing') { $dashboard->loadMissing([ 'sharedUsers', 'shareLinks' => function($query) { $query->where('expires_at', '>', now()); } ]); } return $dashboard; } }以下是仪表板数据加载程序的示例:
<!-- Syntax highlighted by torchlight.dev -->// GET /dashboard/1?section=analytics { "id": 1, "name": "Sales Overview", "widgets": [ { "id": 1, "type": "chart", "viewHistory": [ { "viewed_at": "2024-02-01T10:30:00Z", "views": 150 } ], "interactions": [ { "type": "filter_change", "timestamp": "2024-02-01T11:20:00Z" } ] } ] }
>加载提供了一种管理关系加载,优化数据库查询的有效方法,同时保持代码灵活性。
以上是Laravel的动态关系加载的详细内容。更多信息请关注PHP中文网其他相关文章!