[英]Can I manually eager load a model with data in Laravel Eloquent?
For example say I have Book and Author models.例如说我有 Book 和 Author 模型。 I'd eager load the authors like this:
我渴望像这样加载作者:
$books = Book::with('author')->get();
But I have already fetched the list of authors with Author::all()
in order to display them elsewhere on the page (a select field for filtering).但是我已经使用
Author::all()
获取了作者列表,以便在页面的其他位置显示它们(用于过滤的 select 字段)。 So now Laravel executes 3 queries:所以现在 Laravel 执行 3 个查询:
select * from authors;
select * from books;
select * from authors where id in (1, 2, 3, ...);
The third query is obviously superfluous since I already have the authors.第三个查询显然是多余的,因为我已经有了作者。 Is there some way to pass my
$authors
Collection into my Book query?有什么方法可以将我的
$authors
Collection 传递到我的 Book 查询中吗? Searched through the docs and API and can't find anything.通过文档和 API 搜索,找不到任何东西。
You can use this custom code您可以使用此自定义代码
$authors = Author::get();
$books = Book::get();
foreach ($books as $book) {
$author = $authors->where('id', $book->author_id)->first();
$book->setRelation('author', $author);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.