Framework: [Proposal] Eloquent Model method 'createMany'

Created on 7 Aug 2014  路  6Comments  路  Source: laravel/framework

I propose an addition of a 'createMany' method to the \Illuminate\Database\Eloquent\Model class;

My current solution:

/**
 * Save multiple new models and return an array of the instances.
 *
 * @param  array  $attributeCollections
 * @return static
 */
public static function createMany(array $attributeCollections = array())
{
    return array_map('self::create', $attributeCollections);
}

I find this helpful when writing my db seeding.

Most helpful comment

I'd like to have some kind of method like this (that works with timestamps) on the base model class for writing seeders where the data may be manually entered.

Currently my solution is to iterate over an array and call create for each one. Would be nice to move this down a level, albeit not critical.

All 6 comments

I don't think createMany is a good method name, since it feels doing something with relationships.

It's a common task and would be useful. Maybe this could be implemented directly on the create method, checking for nested arrays. What do you think?

Example:

public static function create(array $attributes) 
{
    if (!empty($attributes) && gettype(current($attributes))=="array")
    {
        return array_map(array('self', 'create'), $attributes);
    }
    // ...
}

Yeah, that sounds good. I was a bit iffy on the name myself. As long as the functionality is somewhere, I'm happy :)

gettype(current($attributes))=="array" wow, why not just, you know, is_array

There seems to be no interest.

I'd like to have some kind of method like this (that works with timestamps) on the base model class for writing seeders where the data may be manually entered.

Currently my solution is to iterate over an array and call create for each one. Would be nice to move this down a level, albeit not critical.

^ what he said.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

PhiloNL picture PhiloNL  路  3Comments

iivanov2 picture iivanov2  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments

kerbylav picture kerbylav  路  3Comments