Reputation: 237
I have three tables users,roles and role_user I want to insert record on that tables with minimum query using eloquent. My current code of insertation
User::create([
'name' => 'admin',
'email' => '[email protected]',
'password' => bcrypt('admin123'),
]);
//create default roles while installation of application
$roles = array(
array('name' => 'admin', 'display_name' => 'Administrator User', 'description' => 'system admin user'),
array('name' => 'registered', 'display_name' => 'Registered User', 'description' => 'free user')
);
foreach ($roles as $key => $role)
{
Role::create($role);
}
//relation between users and roles
User::find(1)->roles()->attach(1);
In above code i am creating a user then creating two roles then inserting record in pivot table(role_user)
. I want to know is there any otherway that i insert the record on these table at same time with one eloquent query Or there is anyother better way?
Upvotes: 4
Views: 1298
Reputation: 5324
Unfortunately it is not possible to insert rows in more than one table at the same time.
Best what I can think of is that:
$user = User::create([
'name' => 'admin',
'email' => '[email protected]',
'password' => bcrypt('admin123'),
]);
//create default roles while installation of application
$roles = [
['name' => 'admin', 'display_name' => 'Administrator User', 'description' => 'system admin user'],
['name' => 'registered', 'display_name' => 'Registered User', 'description' => 'free user']
];
Role::insert($roles);
//relation between users and roles
$user->roles()->attach(1);
With this example You save two queries:
insert
query, instead of two when inserting roles;User
from database - using variable instead;Upvotes: 1