如何在没有 Eloquent 的情况下创建 Laravel 模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21111847/
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:52:32  来源:igfitidea点击:

How to create Laravel Model without Eloquent?

phpormlaravellaravel-4eloquent

提问by Volatil3

As I am not sure, is it possible to create models with DB Class instead of Eloquent? I want to stay away from ORM.

我不确定,是否可以使用 DB Class 而不是 Eloquent 创建模型?我想远离 ORM。

Thanks

谢谢

回答by SwiftD

Yes of course its possible. You dont need to extend any class to make a model class that encapsulates business logic and consists of methods calling the DB class.

是的,当然有可能。您不需要扩展任何类来创建一个封装业务逻辑并由调用 DB 类的方法组成的模型类。

Just create your model inside app/models/MyModel.phplike this

app/models/MyModel.php就像这样在里面创建你的模型

class MyModel{

    public static function getMyData(){
         DB::table('users')->select('column')->get();

    }
}

then you should be fine to call your new class statically:

那么你应该可以静态调用你的新类:

$data = MyModel::getMyData();

If you wanted to extend the DB class you could, though more likely you would be looking to extend the Database/Builder class to extend functionality but this is a complex topic and I suspect you would have asked a very different question if this was what you were after.

如果您想扩展 DB 类,您可以,尽管您更有可能希望扩展 Database/Builder 类以扩展功能,但这是一个复杂的主题,我怀疑您是否会问一个非常不同的问题,如果这是您的之后。

As I final note, I wouldn't steer clear of Eloquent, it's the greatest thing about Laravel amongst a lot of other great things

正如我最后要指出的,我不会避开 Eloquent,它是 Laravel 中最伟大的事情之一

回答by m1kfb

Just remove the "extends Eloquent" and build the queries using the DB class.

只需删除“extends Eloquent”并使用 DB 类构建查询。