Dè a th’ ann an Laravel Eloquent, mar a chleachdas tu e, oideachadh le eisimpleirean
Tha frèam PHP Laravel a’ toirt a-steach Eloquent.
Is e ORM a th’ ann an eloquent, ie Mapper Relational Object.
Tha Eloquent a’ toirt seachad dòigh air leth sìmplidh airson conaltradh le stòr-dàta.
Laravel
e Eloquent
bidh iad a’ cuideachadh le bhith a’ luathachadh tagradh agus leasachadh àrd-ùrlair, a’ toirt seachad fuasgladh iomchaidh don mhòr-chuid de dhuilgheadasan riaghlaidh dàta structaraichte. Thathas a’ dèiligeadh ri riatanasan le leasachadh nas luaithe, a bharrachd air còd air a dheagh eagrachadh, ath-chleachdadh, cumail suas agus scalable.
Ùine leughaidh tuairmseach: 9 minuti
Mar a tha eloquent ag obair
Ag obair le Eloquent
tha e a’ ciallachadh a bhith a’ stiùireadh fiosrachadh, an làthair eadhon ann an grunn stòran-dàta, gu h-èifeachdach a 'cleachdadh aon bhuileachadh Modh Gnìomhach. Is e modail ailtireil a th 'ann far an deach am modail a chruthachadh anns an structar Modail-Sealladh-Stiùiriche (MVC), a' maidseadh clàr anns an stòr-dàta. Is e a 'bhuannachd a th' ann gu bheil na modailean a 'coileanadh obraichean de stòr-dàta cumanta gun a bhith a’ còdadh cheistean fada SQL.
Leigidh teamplaidean leat dàta a cheasnachadh ann an clàran agus clàran ùra a chuir a-steach do chlàran. Tha am pròiseas sioncronaich barrachd stòr-dàta tha ruith air diofar shiostaman air a dhèanamh nas sìmplidhe. Chan fheum thu ceistean SQL a sgrìobhadh. Chan eil agad ach na clàran a mhìneachadh stòr-dàta agus na dàimhean a tha eatorra, agus Eloquent nì a' chuid eile den obair.
Ullachadh laravel
Is iad na ceumannan a bu chòir a ghabhail gus tòiseachadh ag obair air Eloquent:
- Stàlaich Laravel bho getcomposer.org, gus seo a dhèanamh lean an stiùireadh an seo
- Cruthaich
migration
a 'cleachdadh a' chonsailArtisan
- Cruthaich teamplaidean
eloquent
- ruith i
seed
del stòr-dàta
Artisan Console
is e ainm an eadar-aghaidh Command Line
air a ghabhail a-steach ann an Laravel. A’ toirt seachad sreath de dh’ àitheantan feumail airson an cleachdadh nuair a thathar a’ leasachadh tagradh.
Gus liosta fhaicinn de na h-òrdughan Artisan a tha rim faighinn, faodaidh tu an òrdugh liosta a chleachdadh:
php artisan list
No gu sìmplidh php artisan
, a 'faighinn toradh mar seo:
php artisan list
Laravel Framework 9.52.4
Usage:
command [options] [arguments]
Options:
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
about Display basic information about your application
clear-compiled Remove the compiled class file
completion Dump the shell completion script
db Start a new database CLI session
docs Access the Laravel documentation
down Put the application into maintenance / demo mode
env Display the current framework environment
help Display help for a command
inspire Display an inspiring quote
list List commands
migrate Run the database migrations
optimize Cache the framework bootstrap files
serve Serve the application on the PHP development server
test Run the application tests
tinker Interact with your application
ui Swap the front-end scaffolding for the application
up Bring the application out of maintenance mode
auth
auth:clear-resets Flush expired password reset tokens
cache
cache:clear Flush the application cache
cache:forget Remove an item from the cache
cache:table Create a migration for the cache database table
config
config:cache Create a cache file for faster configuration loading
config:clear Remove the configuration cache file
db
db:monitor Monitor the number of connections on the specified database
db:seed Seed the database with records
db:show Display information about the given database
db:table Display information about the given database table
db:wipe Drop all tables, views, and types
env
env:decrypt Decrypt an environment file
env:encrypt Encrypt an environment file
event
event:cache Discover and cache the application's events and listeners
event:clear Clear all cached events and listeners
event:generate Generate the missing events and listeners based on registration
event:list List the application's events and listeners
key
key:generate Set the application key
make
make:cast Create a new custom Eloquent cast class
make:channel Create a new channel class
make:command Create a new Artisan command
make:component Create a new view component class
make:controller Create a new controller class
make:event Create a new event class
make:exception Create a new custom exception class
make:factory Create a new model factory
make:job Create a new job class
make:listener Create a new event listener class
make:mail Create a new email class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:notification Create a new notification class
make:observer Create a new observer class
make:policy Create a new policy class
make:provider Create a new service provider class
make:request Create a new form request class
make:resource Create a new resource
make:rule Create a new validation rule
make:scope Create a new scope class
make:seeder Create a new seeder class
make:test Create a new test class
migrate
migrate:fresh Drop all tables and re-run all migrations
migrate:install Create the migration repository
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
migrate:status Show the status of each migration
model
model:prune Prune models that are no longer needed
model:show Show information about an Eloquent model
notifications
notifications:table Create a migration for the notifications table
optimize
optimize:clear Remove the cached bootstrap files
package
package:discover Rebuild the cached package manifest
permission
permission:cache-reset Reset the permission cache
permission:create-permission Create a permission
permission:create-permission-routes Create a permission routes.
permission:create-role Create a role
permission:setup-teams Setup the teams feature by generating the associated migration.
permission:show Show a table of roles and permissions per guard
queue
queue:batches-table Create a migration for the batches database table
queue:clear Delete all of the jobs from the specified queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:monitor Monitor the size of the specified queues
queue:prune-batches Prune stale entries from the batches database
queue:prune-failed Prune stale entries from the failed jobs table
queue:restart Restart queue worker daemons after their current job
queue:retry Retry a failed queue job
queue:retry-batch Retry the failed jobs for a batch
queue:table Create a migration for the queue jobs database table
queue:work Start processing jobs on the queue as a daemon
route
route:cache Create a route cache file for faster route registration
route:clear Remove the route cache file
route:list List all registered routes
sail
sail:add Add a service to an existing Sail installation
sail:install Install Laravel Sail's default Docker Compose file
sail:publish Publish the Laravel Sail Docker files
sanctum
sanctum:prune-expired Prune tokens expired for more than specified number of hours.
schedule
schedule:clear-cache Delete the cached mutex files created by scheduler
schedule:list List all scheduled tasks
schedule:run Run the scheduled commands
schedule:test Run a scheduled command
schedule:work Start the schedule worker
schema
schema:dump Dump the given database schema
session
session:table Create a migration for the session database table
storage
storage:link Create the symbolic links configured for the application
stub
stub:publish Publish all stubs that are available for customization
ui
ui:auth Scaffold basic login and registration views and routes
ui:controllers Scaffold the authentication controllers
vendor
vendor:publish Publish any publishable assets from vendor packages
view
view:cache Compile all of the application's Blade templates
view:clear Clear all compiled view files
Bidh a h-uile àithne a’ tighinn le tuairisgeul goirid air na h-argamaidean agus na roghainnean aige. Tha seo ri fhaicinn ann an scrion “cuideachadh”. Gus scrion cuideachaidh fhaicinn, dìreach cuir “help” air thoiseach air an ainm àithne mar a chithear:
php artisan help migrate
Description:
Run the database migrations
Usage:
migrate [options]
Options:
--database[=DATABASE] The database connection to use
--force Force the operation to run when in production
--path[=PATH] The path(s) to the migrations files to be executed (multiple values allowed)
--realpath Indicate any provided migration file paths are pre-resolved absolute paths
--schema-path[=SCHEMA-PATH] The path to a schema dump file
--pretend Dump the SQL queries that would be run
--seed Indicates if the seed task should be re-run
--seeder[=SEEDER] The class name of the root seeder
--step Force the migrations to be run so they can be rolled back individually
--isolated[=ISOLATED] Do not run the command if another instance of the command is already running [default: false]
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Migration
Is e pròiseas riaghlaidh a th’ ann an imrich stòr-dàta sgrìobhadh PHP na àite SQL
. A’ toirt seachad dòigh air smachd dreach a chur ris an stòr-dàta.
Gus imrich a chruthachadh, dìreach ruith an òrdugh a leanas:
php artisan make:migration create_student_records
Cruthaichidh seo am faidhle imrich. Anns an deasaiche teacsa agad, fosgail am faidhle a chruthaich thu sa phasgan database\migrations
:
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateStudentRecordsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('student__records', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('student__records');
}
}
'S e clas leis an aon ainm a th' anns a' chòd'create student records
', agus tha dà dhòigh ann: up
e down
. An dòigh-obrach up
bu chòir atharraichean a dhèanamh air an stòr-dàta; mar sin a h-uile uair a nì thu imrich stòr-dàta, thèid còd sam bith sa mhodh a chur gu bàs up
. Air an làimh eile, bu chòir don dòigh sìos na h-atharrachaidhean sin a thilleadh air ais stòr-dàta; mar sin a h-uile uair a ruitheas tu an rollback
della migration
, bu chòir don dòigh sìos na rinn am modh a thoirt air falbh up
. Taobh a-staigh an dòigh-obrach up
tha an neach-togail sgeamaichean air a chleachdadh gus na bùird a chruthachadh agus a làimhseachadh. Dè thachras ma chuireas tu dheth cuid de na h-imrich agad? Chan eil agad ach an òrdugh a leanas a chuir an gnìomh:
php artisan migrate:rollback
Agus cruinnichidh e am fear mu dheireadh migration
a chaidh a chur an gnìomh. A bharrachd air an sin, faodaidh tu am faidhle ath-nuadhachadh gu tur stòr-dàta a' ruith:
php artisan migrate:reset
Cuiridh seo dheth na h-imrich agad gu lèir.
Mìneachadh air modailean Eloquent
Aon uair 's gu bheil an gluasad deiseil stòr-dàta, is e an ath phròiseas an seeding
. Eloquent
air tighinn a-steach bhon uair sin seeding
a’ cur chlàran a-steach don ar-a-mach againn stòr-dàta. Mar sin feumaidh tu na teamplaidean a chruthachadh mus cuir thu a-steach am faidhle stòr-dàta. A h-uile clàr de stòr-dàta tha modail co-fhreagarrach aige a tha air a chleachdadh gus eadar-obrachadh leis a’ chlàr sin. Leigidh teamplaidean leat dàta a cheasnachadh anns na clàran agad, a bharrachd air clàran ùra a chuir a-steach don chlàr. Is e an dòigh as fhasa am modail a chuir an gnìomh an òrdugh a leanas a chleachdadh:
php artisan make:model Student
Tha eisimpleir de theamplaid ri fhaicinn gu h-ìosal Student
, a dh’fhaodar a chleachdadh airson fiosrachadh fhaighinn air ais agus a stòradh bhon chlàr stòr-dàta den oileanach againn:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Student extends Model
{
//
}
Nuair a bhios tu a ghineadh modail agus aig an aon àm ag iarraidh a ghineadh imrich de na stòr-dàta, faodaidh tu an roghainn a chleachdadh –migration
o -m
:
php artisan make:model Student --migration
php artisan make:model Student -m
Fillable
e Guarded
In Laravel
, bi $fillable
a $guarded
bidh iad air an cleachdadh gus smachd a chumail air sònrachadh mòr buadhan anns na modailean agad. Dèanamaid sgrùdadh air na h-eadar-dhealachaidhean:
$fillable
:
- Bidh e ag obair mar “liosta geal” de bhuadhan a dh’ fhaodar a shònrachadh gu ìre mhòr.
- Bidh thu a’ sònrachadh gu soilleir dè na buadhan a tha ceadaichte airson mòr-shònrachadh.
- Chan urrainnear ach na buadhan air an liostadh ann an $fillable a shuidheachadh le fill() le sreath de luachan.
eisimpleir:
class User extends Eloquent {
protected $fillable = ['name', 'email'];
}
Anns an eisimpleir seo chan urrainnear ach na h-ainmean agus na colbhan post-d a shònrachadh gu ìre mhòr.
$ dìon:
- Tha e ag obair mar “liosta dhubh” de bhuadhan nach bu chòir a shònrachadh en masse.
- Bidh thu a’ sònrachadh gu soilleir dè na buadhan a bu chòir a bhith air an dìon bho mhòr-shònrachadh.
- Tha na feartan air an liostadh ann an
$guarded
cha bhi iad air an suidheachadh le cleachdadhfill()
.
eisimpleir:
class User extends Eloquent {
protected $guarded = ['name', 'email'];
}
Anns a 'chùis seo, cha ghabh na h-ainmean agus na colbhan post-dealain gu mòr a shònrachadh.
A 'cur an dà chuid còmhla:
Faodaidh tu an dà chuid a chleachdadh $fillable
a $guarded
còmhla.
Ma tha thu airson a h-uile raon ach beagan raointean a shònrachadh gu mòr, cleachd sreath $guarded
falamh:
protected $guarded = [];
Ma tha thu airson casg a chuir air a h-uile raon bho bhith air a shònrachadh gu mòr, cleachd:
protected $guarded = ['*'];
Ma tha thu airson raointean sònraichte a dhìon, cleachd $fillable
airson raointean a bhith air an lìonadh gu mòr e $guarded
airson a' chòrr.
Seiders
I seeder
gu h-iomlan tha seata sònraichte de chlasaichean a leigeas leinn ar sluagh a ghabhail stòr-dàta a-rithist agus a-rithist leis an aon dearbh dàta. Bidh sinn a’ cur an gnìomh an òrdugh a leanas:
php artisan make:seeder StudentsRecordSeeder
Anns an deasaiche teacsa, fon phasgan seeds
, fosgail am faidhle ùr-chruthaichte le ainm faidhle: StudentsRecordSeeder.php
. Mar a chì thu, is e dìreach clas gu math sìmplidh a tha seo le aon dòigh ris an canar run()
.
<?php
use IlluminateDatabaseSeeder;
class StudentsRecordSeeder extends Seeder
{
/**
* Run the database seeds
* @return void
*/
public function run()
{
//
}
}
Chan eil anns a’ chòd ach pasgan timcheall air clas àithne tòcan, a chaidh a thogail gu sònraichte gus cuideachadh le obair seeding
. Deasaich an còd agus an uairsin sàbhail e.
public function run()
{
echo 'Seeding!';
}
Agus a’ dol chun cheann-uidhe, tòisich an àithne neach-ciùird gus modh ruith a’ chlas ùr-chruthaichte a chuir an gnìomh:
php artisan db:seed --class=StudentsRecordSeeder
Ma tha thu airson feuchainn ri eisimpleir clas sìolaidh a chuir an gnìomh, faodaidh tu leantainn air adhart a’ leughadh ar post.
A-nis is urrainn dhuinn cumail oirnn a’ cur an gnìomh gnìomhachd DB gu lèir le Eloquent.
CRUD le Laravel Eloquent
Le operazioni RAW le Laravel Eloquent object-relational mapper (ORM)
bidh iad ga dhèanamh nas fhasa do luchd-leasachaidh Laravel obrachadh le barrachd stòr-dàta. Esegue operazioni di creazione, lettura, aggiornamento ed eliminazione (RAW), nonché mappa i modelli di oggetti alle tabelle del stòr-dàta. A 'riaghladh a h-uile eadar-obrachadh de na stòr-dàta richieste per le operazioni RAW.
Cruthachadh chlàran
Faodaidh tu an dòigh ::create a chleachdadh gus clàr ùr a chuir a-steach don fhaidhle stòr-dàta.
student_record::create(array(
'first_name' => 'John',
'last_name' => 'Doe',
'student_rank' => 1
));
A bharrachd air an dòigh cruthachaidh sìmplidh a chithear gu h-àrd, faodaidh tu cuideachd rud ùr a chruthachadh agus buadhan eadar-dhealaichte a thoirt dha. An uairsin, faodaidh tu an gnìomh sàbhaladh () a ghairm agus an còd a ruith. Dòighean-obrach mar firstOrCreate()
o firstOrNew()
tha roghainnean eile ann airson clàran a chruthachadh. Leigidh iad sin leat oileanach a lorg le buadhan sònraichte; mura lorgar an oileanach sin, cruthaichidh tu e anns an stòr-dàta no cuiridh tu sa bhad eisimpleir ùr.
firstOrCreate()
Rannsaich airson clàr a’ cleachdadh na paidhrichean prìomh-luach ainmichte. Mura lorgar am modail anns an stòr-dàta, a’ cruthachadh clàr ùr leis na buadhan ainmichte. Feumaidh am paidhir luach bunaiteach a bhith air a thoirt seachad mar iuchair ceangail.
Example: Can gu bheil a model User
agus ag iarraidh neach-cleachdaidh a lorg no a chruthachadh stèidhichte air an t-seòladh post-d aca:
$user = User::firstOrCreate(['email' => 'user@example.com']);
Ma tha neach-cleachdaidh ann leis an t-seòladh post-d “user@example.com”, an firstOrCreate
bheir an cleachdaiche sin air ais. Mura lorgar maids, thèid cleachdaiche ùr a chruthachadh leis an t-seòladh post-d ainmichte.
Eisimpleir le buadhan sònraichte: Ma tha thu airson dèanamh cinnteach nach eil ann ach aon raon sònraichte (mar eisimpleir, post-d), ach cuideachd sgrìobh feadhainn eile, faodaidh tu sreath aon-eileamaid a thoirt seachad leis an raon a tha thu ag iarraidh.
$user = User::firstOrCreate(['email' => 'user@example.com'], ['name' => 'John Doe']);
Ma tha neach-cleachdaidh ann leis a’ phost-d “user@example.com”, firstOrCreate
a 'tilleadh an neach-cleachdaidh sin. Rud eile, cruthaichidh e neach-cleachdaidh ùr leis a’ phost-d agus an t-ainm “John Doe”.
firstOrNew()
An dòigh firstOrNew
air a chleachdadh gus a’ chiad mhodail a lorg a choinnicheas ri cumhachan sònraichte. Mura lorgar teamplaid maidsidh, cruthaichidh tu eisimpleir ùr den teamplaid ach cha shàbhail sin e stòr-dàta.
$user = User::firstOrNew(['email' => 'user@example.com']);
Ma tha cleachdaiche ann leis an t-seòladh post-d “user@example.com”, tillidh e an cleachdaiche sin. Rud eile, cruthaichidh e eisimpleir cleachdaiche ùr leis a’ phost-d ainmichte. Faodaidh tu cuideachd buadhan a bharrachd a chuir seachad nuair a chruthaicheas tu an eisimpleir ùr:
$user = User::firstOrNew(['email' => 'user@example.com'], ['name' => 'John Doe']);
Mura lorgar cleachdaiche gnàthaichte, thèid cleachdaiche ùr a chruthachadh leis a’ phost-d agus an t-ainm “John Doe”.
An dà dhòigh firstOrCreate
e firstOrNew
tha iad coltach. An dòigh-obrach firstOrCreate
feuchainn ri pàtran a lorg a fhreagras ris na buadhan ainmichte. Mura lorgar e, cruthaichidh agus sàbhailidh e teamplaid ùr gu fèin-ghluasadach fhad ‘s a tha e firstOrNew
mura lorg e e, cruthaichidh e an eisimpleir ach cha shàbhail e e. Mura sàbhail thu, feumaidh tu buadhan sam bith a sgrìobhadh agus an uairsin a shàbhaladh.
A’ leughadh chlàran
A’ cleachdadh Eloquent ORM, gheibh thu clàran anns an stòr-dàta. Tha ceistean air an togail gu sìmplidh agus a’ tabhann sruthadh rèidh. Gus stiùireadh a chruthachadh ::where
, cleachdaidh tu na dòighean get
() Agus first
,
An dòigh first
() cha till ach aon chlàr, fhad 'sa bhios am modh get
() tillidh e sreath de chlàran as urrainn dhut a lùbadh troimhe gus na toraidhean gu lèir a leughadh. A bharrachd air an sin, an dòigh-obrach find
() faodar a chleachdadh le sreath de phrìomh iuchraichean, a thilleas cruinneachadh de chlàran maidsidh.
Ecco alcuni empi:
$student = Students::all();
Bidh an còd seo a’ faighinn a h-uile oileanach. Fhad ‘s a lorgas an còd a leanas oileanach sònraichte le ID:
$oileanach = Oileanaich:: lorg(1);
Cuideachd, mar a chithear gu h-ìosal, tha an còd ag innse mu bhith a’ lorg oileanach stèidhichte air feart sònraichte.
$JohnDoe = Students::where('name', '=', 'John Doe')->first();
Airson an dòigh get(), tha an còd seo a’ sealltainn mar a lorgas tu oileanach le ìre os cionn 5.
$rankStudents = Student::where('student_rank', '>', 5)->get();
Ùrachadh clàr
Tha e a cheart cho furasta clàran ùrachadh le bhith a’ cleachdadh Eloquent. Gus clàr ùrachadh, dìreach lorg an clàr a tha thu airson ùrachadh, deasaich na buadhan agus sàbhail. Mar eisimpleir, gus ìre ìre oileanach John Doe atharrachadh gu 5, lorg an oileanach an toiseach agus an uairsin cuir an gnìomh am modh sàbhalaidh.
$JohnDoe = Bear::where('name', '=', 'John Doe')->first();
$JohnDoe->danger_level = 5;
$JohnDoe->save();
Faodar an dòigh sàbhalaidh a chleachdadh cuideachd gus na modalan a tha ann mu thràth ùrachadh anns an fhaidhle stòr-dàta.
Sguab às clàran
Tha Eloquent a’ bòstadh den phròiseas ùrachadh chlàran furasta aige, ach tha an aon sgeulachd aige ri sguabadh às. Tha dà roghainn ann: clàran tarraing a-mach agus cuir an gnìomh an dòigh sguabaidh às, no dìreach cleachd am modh sgrios. Gus clàr a lorg agus a dhubhadh às, dìreach ruith na h-òrdughan a leanas:
$student = Students::find(1);
$student->delete();
Gus clàr agus grunn chlàran a dhubhadh às, tha na h-òrdughan air an ruith:
Students::destroy(1);
Students::destroy(1, 2, 3);
Thoir an aire gur e prìomh iuchraichean an sgrios a-mhàin eu-coltach ris an dòigh sguabaidh às as urrainn gabhail ri colbh sam bith stòr-dàta.
Airson a h-uile oileanach os cionn ìre 10 a lorg agus a sguabadh às.
Students::where('student_rank', '>', 10)->delete();
Leughaidhean Co-cheangailte
Ercole Palmeri