php Laravel“未定义的方法Illuminate\Database\Query\Builder::attach()”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22495130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel "undefined method Illuminate\Database\Query\Builder::attach()"
提问by glasstree
I'm trying to associate related models during database seeding in Laravel 4. According to the documentation here, I can do it like this:
我正在尝试在 Laravel 4 中的数据库播种期间关联相关模型。根据此处的文档,我可以这样做:
$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:
包裹项目此时已经播种,它们播种没有问题。上面的代码虽然从 Artisan 给出了这个:
[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::attach()
Someone hereseems to think that the attach()method doesn't actually exist and the docs are wrong, but I find that hard to believe.
这里有人似乎认为该attach()方法实际上并不存在并且文档是错误的,但我发现这很难相信。
TL;DR What is the correct way to create many-to-many relationships in Eloquent?
TL;DR 在 Eloquent 中创建多对多关系的正确方法是什么?

