Laravel 制作模型
例子
模型制作
模型类必须扩展Illuminate\Database\Eloquent\Model。模型的默认位置是/app目录。
可以通过Artisan命令轻松生成模型类:
php artisan make:model [ModelName]
这将app/默认创建一个名为的新PHP文件[ModelName].php,并将包含新模型的所有样板,包括基本设置所需的类,名称空间和using。
如果要与模型一起创建迁移文件,请使用以下命令,其中-m还将生成迁移文件:
php artisan make:model [ModelName] -m
Inadditiontocreatingthemodel,thiscreatesadatabasemigrationthatishookeduptothemodel.ThedatabasemigrationPHPfileislocatedbydefaultindatabase/migrations/.Thisdoesnot--bydefault--includeanythingotherthantheidandcreated_at/updated_atcolumns,soyouwillneedtoeditthefiletoprovideadditionalcolumns.
Notethatyouwillhavetorunthemigration(onceyouhavesetupthemigrationfile)inorderforthemodeltostartworkingbyusingphpartisanmigratefromprojectroot
Inaddition,ifyouwishtoaddamigrationlater,aftermakingthemodel,youcandosobyrunning:
php artisan make:migration [migration name]
SayforexampleyouwantedtocreateamodelforyourCats,youwouldhavetwochoices,tocreatewithorwithoutamigration.Youwouldchosetocreatewithoutmigrationifyoualreadyhadacatstableordidnotwanttocreateoneatthistime.
Forthisexamplewewanttocreateamigrationbecausewedon'talreadyhaveatablesowouldrunthefollowingcommand.
php artisan make:model Cat -m
Thiscommandwillcreatetwofiles:
IntheAppfolder:app/Cat.php
Inthedatabasefolder:database/migrations/timestamp_creat_cats_table.php
Thefileweareinterestedinisthelatterasitisthisfilethatwecandecidewhatwewantthetabletolooklikeandinclude.Foranypredefinedmigrationwearegivenanautoincrementingidcolumnandatimestampscolumns.
Thebelowexampleofanextractofthemigrationfileincludestheabovepredefinedcolumnsaswellastheadditionofathenameofthecat,ageandcolour:
public function up() { Schema::create('cats', function (Blueprint $table) { $table->increments('id'); //预定义ID $table->string('name'); //Name $table->integer('age'); //Age $table->string('colour'); //Colour $table->timestamps(); //预定义时间戳 }); }
Soasyoucanseeitisrelativelyeasytocreatethemodelandmigrationforatable.Thentoexecutethemigrationandcreateitinyourdatabaseyouwouldrunthefollowingcommand:
php artisan migrate
Whichwillmigrateanyoutstandingmigrationstoyourdatabase.
ModelFileLocation
ModelscanbestoredanywherethankstoPSR4.
BydefaultmodelsarecreatedintheappdirectorywiththenamespaceofApp.Formorecomplexapplicationsit'susuallyrecommendedtostoremodelswithintheirownfoldersinastructurethatmakessensetoyourappsarchitecture.
例如,如果您有一个使用一系列水果作为模型的应用程序,则可以创建一个名为的文件夹,app/Fruits并在创建的该文件夹内Banana.php(保持StudlyCase命名约定),然后可以在App\Fruits名称空间中创建Banana类:
namespace App\Fruits; use Illuminate\Database\Eloquent\Model; class Banana extends Model { // Implementation of "Banana" omitted }
型号配置
雄辩的遵循“约定之上的配置”方法。通过扩展基Model类,所有模型都继承下面列出的属性。除非覆盖,否则将应用以下默认值: