包含多个类的 Laravel 模型 [英] Laravel model containing multiple classes
问题描述
我是 laravel 的新手,来自 Codeigntier.我试图掌握 Laravel 使用的模型/类/雄辩的约定.我知道我可以在我的数据库中创建一个名为类别"的表.然后我可以在我的模型文件夹中创建一个名为 category.php 的文件,其中只包含以下代码:
I'm new to laravel, coming from Codeigntier. I am trying to get to grips with the model/classes/eloquent convention that Laravel uses. I know that I can make a table in my database called, say, "categories". Then I can make a file in my models folder called category.php containing just the following code:
Class Category extends Eloquent { }
它会自动连接带有复数版本名称(类别")的表名,并让我可以访问我的控制器中的所有 Eloquent 命令,例如 Category::All();
which automatically connects with the table name with the plural version of the name ("categories") and gives me access to all the Eloquent commands in my controller like Category::All();
以下是我不明白的:我是否需要为数据库中的每个表创建一个新模型?在这种情况下,我的模型文件夹中会出现一堆文件,名称如 resource1.php、resource2.php 等,每个文件都包含与上面相同的代码(替换类的名称).
Here's what I don't get: Do I need to make a new model for every table in my database? In that case I will end up with a bunch of files in my models folder with names like resource1.php, resource2.php, etc, each just containing the same code as above (replacing the name of the class).
我不能只创建一个模型,例如database_handler.php",然后将所有这些类放在同一个地方吗?
Can't I just make one model called, say, "database_handler.php" and then just put all these classes into it in the same place?
推荐答案
是的,您可以创建一个 database_handler.php
文件并执行以下操作:
Yes, you can create a database_handler.php
file and do:
<?php
Class Category extends Eloquent { }
Class Post extends Eloquent { }
Class Client extends Eloquent { }
您可以做任何 PHP 让您做的事情,将许多类添加到单个 .php
文件是您可以做的事情.但这不是一个好的做法,Laravel 就是要使用最好的开发应用程序.
You can do whatever PHP let's you do, and add many classes to a single .php
file is something you can do. But this is not a good practice and Laravel is all about developing application using the best ones.
要自动加载此文件,您可以执行以下操作之一:
To load this file automatically, you can do one of many things:
1) 将此文件添加到您的 app/models 文件夹中.
1) Add this file to your app/models folder.
2) 在您的 composer.json 中为其添加一个条目:
2) Add an entry for it on your composer.json:
"autoload": {
"files": [
"app/database_handler.php"
]
},
然后你将不得不
composer dump-autoload -o
3) 为其创建一个不同的文件夹并将其添加到 composer json 自动加载部分.
3) Create a different folder for it and also add it to composer json autoload section.
你选择,Laravel 会让你自由地做任何你想做的事情.
You choose, Laravel will let you free to do whatever you want.
这篇关于包含多个类的 Laravel 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!