问题
I'm trying to associate related models during database seeding in Laravel 4. According to the documentation here, I can do it like this:
$user->roles()->attach(1);
So, in my database seed I'm running:
$package = Package::create([
'name' => $faker->word,
'summary' => $faker->sentence,
'base_price' => $faker->randomFloat(2, 200, 10000)
]);
// Attach 1-5 randomly selected items to this package
foreach(range(1, 5) as $index)
{
$randomItem = Item::orderBy(DB::raw('RAND()'))->first();
$package->items()->attach($randomItem->id);
}
The packages items have already been seeded at this point, and they seed without problems. The above code gives this from Artisan though:
[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::attach()
Someone here seems to think that the attach()
method doesn't actually exist and the docs are wrong, but I find that hard to believe.
TL;DR What is the correct way to create many-to-many relationships in Eloquent?
回答1:
The function items()
in your Package model has to return a BelongsToMany relationship in order to use attach().
public function items() {
return $this->belongsToMany('Item');
}
来源:https://stackoverflow.com/questions/22495130/laravel-undefined-method-illuminate-database-query-builderattach