Laravel“未定义的方法Illuminate \ Database \ Query \ Builder :: attach()" [英] Laravel "undefined method Illuminate\Database\Query\Builder::attach()"

查看:34
本文介绍了Laravel“未定义的方法Illuminate \ Database \ Query \ Builder :: attach()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Laravel 4的数据库播种期间尝试关联相关模型.根据文档在这里,我可以这样:

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);
}

这时,包项目已被播种,并且播种没有问题.上面的代码虽然是Artisan提供的:

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()

有人此处似乎认为 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在Eloquent中创建多对多关系的正确方法是什么?

推荐答案

包装模型中的函数 items()必须返回 BelongsToMany 附加() .

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');
}

这篇关于Laravel“未定义的方法Illuminate \ Database \ Query \ Builder :: attach()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆