简体   繁体   English

何时在Laravel中使用雄辩的模型

[英]When to use an eloquent model in laravel

I am developing a set of backend APIs which will be used by an android/iphone app. 我正在开发一套将由android / iphone应用程序使用的后端API。 There are instances where I have to use joins of more than 2 or 3 tables. 在某些情况下,我必须使用2个或3个以上表的联接。

For example: 例如:

I have a products table that is associated with its likes, SKU's, comments, and category tables. 我有一个与其喜欢,SKU,注释和类别表相关联的产品表。 If I am using eager loading to get all the values associated with the products table, it's going to execute the following queries: 如果我正在使用紧急加载来获取与产品表相关的所有值,它将执行以下查询:

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')

This has run 4 queries with all '*'. 这已经运行了4个全为*的查询。 If I need to have specific columns to be selected, I will have to hardcode it in the model relationship function and it will not be dynamic. 如果需要选择特定的列,则必须在模型关系函数中对其进行硬编码,并且它不是动态的。 This will kill the performance and scalability of my application. 这将破坏我的应用程序的性能和可伸缩性。

Where does the eloquent model come into play? 雄辩的榜样在哪里发挥作用? Does it just give the advantage of faster development and an abstraction layer from the queries? 它是否只是提供了更快的开发和查询抽象层的优势? Or are there any specific places where I can use eloquent model without compromising performance? 还是在某些特定的地方可以使用雄辩的模型而不影响性能? What I understand is, if I have more tables, I better be using joins rather than eloquent? 我的理解是,如果我有更多的表,我最好使用联接而不是雄辩的?

Eloquent is an ORM. 口才是一个ORM。 This ennables a user to use objective approach to set data and not to worry about how it is stored. 这使用户可以使用客观的方法来设置数据,而不必担心如何存储数据。 No need to worry abbout sql injections and so on. 无需担心abbout sql注入等等。 But every ORM has a drawback. 但是每个ORM都有一个缺点。 On (retrieving) complex data sets raw SQL is much more efficient in allot of cases. 在(检索)复杂数据集上,原始SQL在案件分配中效率更高。 You can execute raw sql like this: 您可以像这样执行原始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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM