Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Model & Seeding 整合

Shengyou Fan
December 07, 2014

Model & Seeding 整合

Shengyou Fan

December 07, 2014
Tweet

More Decks by Shengyou Fan

Other Decks in Programming

Transcript

  1. Model • ౷Ұ์ஔࡏ app/models/{model}.php • ҰݸࢿྉදबੋҰ܈ࢿྉతू߹ɼ㑌Ұච ࢿྉ (row) बሣጯҰݸ Model

    መᱪ • ࡏ Laravel త׳ྫཫɼࢿྉදత໊᜝༻ӳ จෳᏐʀࣕ Model త໊᜝ब༻ӳจᄸᏐ ˒ ჩߟɿhttp://laravel.tw/docs/4.2/eloquent#basic-usage
  2. Model 䈕Ҋ݁ߏ • Ұݸ࠷ਫ਼؆త Model 䈕Ҋ୞धࡾߦ • एཁڧ੍ࢦఆሣጯతࢿྉද໊᜝ɼଇ࠶Ճ Ұߦ class

     Post  extends  \Eloquent { } class  Post  extends  \Eloquent {        protected  $table  =  ‘posts’; }
  3. खಈݐཱ Model • ࡏ app/models/ ఈԼ৽⃧ {‘M’odel (ᄸ Ꮠ)}.php •

    ༌ೖ Model ఔࣜᛰ (ਫ਼؆ࡾߦ) • ࣥߦ php artisan dump-autoload ᩋ৽ݐ޷ త Model ሜೖ class map 㚎
  4. artisan generate:model • 㗞ੜ Model 䈕Ҋ - artisan 㚎ݐᔒ༗㗞ੜ Model

    䈕తࢦྩɼ ୠՄ༻ generator 㗞ੜ • ൣྫɿ $  php  artisan  generate:model  post
  5. Seeds • ౷Ұ์ஔࡏ app/database/seeds/{seed}.php • 䈕Ҋ໋໊׳ྫҝ {‘M’odel ໊᜝}TableSeeder • 㑌Ұݸ

    Seeder 䈕Ҋཫ୞༗Ұݸ run വࣜ • വࣜ㚎ՄҎሜ૝ཁ㗞ੜଌࢼࢿྉతنଇ • هಘཁࡏ DatabaseSeeder ཫݺڣ ˒ ჩߟɿhttp://laravel.tw/docs/migrations#database-seeding
  6. Seeder 䈕Ҋ݁ߏ • Ұݸجૅత Seeder ݁ߏɼ୞༗ run വࣜ class  PostTableSeeder

     extends  Seeder {        public  function  run()        {                //  ࣗߦḤሜ㗞ੜଌࢼࢿྉతنଇ        } }
  7. खಈݐཱ Seeder • ࡏ app/models/ ఈԼ৽⃧ {‘M’odel (ᄸᏐ)} TableSeeder.php •

    ༌ೖ Seeder ఔࣜᛰ (run വࣜ㚎༰) • ࣥߦ php artisan dump-autoload ᩋ৽ݐ޷ త Model ሜೖ class map 㚎
  8. artisan generate:seed • 㗞ੜ Seeder 䈕Ҋ - artisan 㚎ݐᔒ༗㗞ੜ Seeder

    䈕తࢦྩɼ ୠՄ༻ generator 㗞ੜ • ൣྫɿ $  php  artisan  generate:seed  post
  9. artisan db:seed • ࣥߦ Seeding - ݺڣ DatabaseSeederɼ೺ଖதॴ༗త Seeder 䋯Ұว

    - ՃჩᏐ --class={Model}TableSeeder ՄҎ ୞ࣥߦ๭Ұݸ Seeder • ൣྫɿ $  php  artisan  db:seed $  php  artisan  db:seed  -­‐-­‐class=PostTableSeeder
  10. ৽⃧ࢿྉલਗ਼ۭࢿྉ • artisan db:seed ࢦྩ୞။ᄸ७తࣥߦ run త 㚎༰ɼҼࠑएࢦྩҰ௚Լɼ၊ࢿྉब။Ұ ௚⃧Ճ •

    ࢖༻ DB ෺݅ࡏ Seeding ೭લઌਗ਼ۭࢿྉ දɼ၊ࢿྉ࠽ෆ။Ұ௚௕ɺҰ௚௕… • ൣྫɿ DB::table(‘{ࢿྉද໊᜝}’)-­‐>truncate();
  11. ᩋࢿྉଟᴍᬋػײ • ઃఆ rand വࣜ㗞ੜ category_id ٴ post_idɼᩋሣጯՄҎߋᬋػҰࠣ • ༻

    Carbon ߇੍೔ظ࣌ؒత㗞ੜɼᩋࢿྉ ෆ။౎ࡏಉҰఱሜೖ • ൣྫɿ ‘category_id’  =>  rand(1,  4); ‘created_at’  =>  \Carbon\Carbon::now()-­‐>addDays($index); ˒ ჩߟɿhttps://github.com/briannesbitt/Carbon
  12. ᩋ၊ࢿྉߋਅʂ • ഑߹ Faker ౟݅ɼᩋ㗞ੜग़ိతଌࢼࢿྉ ߋ૾ਅతҰᒬ (༗ Fuʂ) • composer.json

    㚎৽⃧ faker ౟݅ɼ࠶ࣥߦ composer update • ሜ Seeder 䈕࣌ɼҾೖ Faker ྨผ • ए࢖༻ generator త࿩ɼ။ࣗಈ㢨㟬ሜ޷ ˒ ჩߟɿhttps://github.com/fzaninotto/Faker
  13. ߋଟ Faker ጯ༻ڭላ • Simplifying Test Data Generation with Faker

    - http://www.sitepoint.com/simplifying-test-data- generation-with-faker/ • Build a Database with Eloquent, Faker and Flysystem - http://www.sitepoint.com/build-database-eloquent- faker-flysystem/
  14. ֊ஈᒾ查ද • ֬ೝ༗㗞ੜ 3 ݸ Model 䈕 • ֬ೝ༗㗞ੜ 3

    ݸ Seeder 䈕ɼฒઃఆ޷ DatabaseSeeder • ֬ೝ DB 㚎ቮៃ༗㗞ੜग़ိతଌࢼࢿྉ