Laravel 4: Working with relationships in seeds

前端 未结 3 556
死守一世寂寞
死守一世寂寞 2021-02-02 15:32

Is there an easy way to manage many-to-many relationships in the new seeds feature of L4?

One way would be to make a seed for the pivot table, but I would be a lot of wo

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 16:16

    Laravel seed files are regular PHP scripts (except they need to return an array). You can query the database in seed files (using Eloquent, Fluent builder or even PDO).

    One way to tackle the many-to-many problem is to deliberately name your seed files so that the pivot table is populated last... For example, you could prepend a numeric value to the file name (i.e. 1_authors.php, 2_books.php, 3_authors_books.php etc.). Artisan sorts the filenames alphabetically before executing them.

    I have posted a small tutorial on Laravel 4 database seeding - this should get you going. Additionally, you may consult the official doc on seeding.

提交回复
热议问题