Laravel “undefined method Illuminate\Database\Query\Builder::attach()”

筅森魡賤 提交于 2021-02-18 20:50:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!