laravel 何时使用 Eloquent (ORM) 而不是 Fluent (Query Builder)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17739931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:09:39  来源:igfitidea点击:

When to use Eloquent (ORM) over Fluent (Query Builder)?

laravellaravel-4eloquent

提问by bitinn

Maybe due to my Codeigniter background, I just don't find myself enjoying Laravel 4's Eloquent ORM a lot. Say I would like to write a query that order a list of posts by id, descending, how can Eloquent beat the clarity of DB::table('posts')->orderBy('id', 'desc')->get();?

也许由于我的 Codeigniter 背景,我发现自己并不喜欢 Laravel 4 的 Eloquent ORM。假设我想编写一个查询,按 id 对帖子列表进行排序,降序,Eloquent 如何超越DB::table('posts')->orderBy('id', 'desc')->get();?

Is there a good reason to use Eloquent over Fluent, was it mostly for joining tables?

是否有充分的理由使用 Eloquent 而不是 Fluent,主要是为了连接表格吗?

回答by Victor

I came from codeigniter also and this is my experience: I use Eloquent and Fluent usually together. Eloquent is a thing that allows you to work nicely with relations, CRUD operations etc. When you need to do some SQL operations you can easily add some fluent functions

我也来自 codeigniter,这是我的经验:我通常一起使用 Eloquent 和 Fluent。Eloquent 是一个可以让你很好地处理关系、CRUD 操作等的东西。当你需要做一些 SQL 操作时,你可以很容易地添加一些流畅的函数

In the example you mentioned above I see you have posts table. If you have a post model then the same thing written using Eloquent is:

在你上面提到的例子中,我看到你有帖子表。如果您有一个后期模型,那么使用 Eloquent 编写的相同内容是:

Post::orderBy('id', 'desc')->get();

So as I get it if you extends Eloquent than

所以据我所知,如果你扩展 Eloquent 比

Model_name::some_functions

is the same as

是相同的

DB::table('table_name')->some_functions

The real power comes when you need to create or update a model, or, for example, get post comments. Than it becomes easily:

当您需要创建或更新模型,或者,例如,获得帖子评论时,真正的力量就来了。比它变得容易:

$comments = Post::find($id)->comments;

So the answer is - you have to use fluent functions to get ordered list. You can use them both with DB::table('posts')->orderBy or Post::orderBy

所以答案是 - 您必须使用流畅的函数来获取有序列表。您可以将它们与 DB::table('posts')->orderBy 或 Post::orderBy 一起使用

回答by Collin Henderson

Using models and Eloquent, you can also write custom functions in your model class for performing common operations like, say, outputting a couple concatenated fields.

使用模型和 Eloquent,您还可以在模型类中编写自定义函数来执行常见操作,比如输出几个连接的字段。

for instance:

例如:

<?php
class User extends Eloquent {
    //Standard Relation Function
    public function posts() {
        return $this->hasMany('Post');
    }
    //Custom function
    public function fullname() {
        return $this->firstName.' '.$this->lastName;
    }
}

//Somewhere else in your code, if you need a users full name...
$user = User::find(3);
$name = $user->fullname();