gpt4 book ai didi

php - 何时在 Laravel 中使用 Eloquent 模型

转载 作者:行者123 更新时间:2023-11-29 21:45:23 25 4
gpt4 key购买 nike

我正在开发一组后端 API,将由 android/iphone 应用程序使用。在某些情况下,我必须使用超过 2 或 3 个表的联接。

例如:

我有一个与其“喜欢”、“SKU”、“评论”和“类别”表关联的产品表。如果我使用急切加载来获取与产品表关联的所有值,它将执行以下查询:

select * from `products` where `products`.`products_id` = '1'
select * from `skus` where `skus`.`products_id` in ('1')
select * from `likes` where `likes`.`products_id` in ('1')
select * from `comments` where `comments`.`products_id` in ('1')

这已运行 4 个全为“*”的查询。如果我需要选择特定的列,我将不得不在模型关系函数中对其进行硬编码,并且它不会是动态的。这会降低我的应用程序的性能和可扩展性。

Eloquent 模型在哪里发挥作用?它是否只是提供了更快的开发和查询抽象层的优势?或者有什么特定的地方可以在不影响性能的情况下使用 Eloquent 模型?我的理解是,如果我有更多表,我最好使用联接而不是 Eloquent ?

最佳答案

Eloquent 是一种 ORM。这使得用户能够使用客观的方法来设置数据,而不必担心它是如何存储的。无需担心sql注入(inject)等问题。但每个 ORM 都有一个缺点。在(检索)复杂数据集时,原始 SQL 在分配情况下效率更高。您可以像这样执行原始 SQL:

$products = \DB::table('products')
->where('products_id', 1)
->join('skus', 'skus.product_id', '=', 'products.product_id')
->join('likes', 'likes.product_id', '=', 'products.product_id')
->join('comments', 'comments.product_id', '=', 'products.product_id');

关于php - 何时在 Laravel 中使用 Eloquent 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com