首页  >  问答  >  正文

laravel使用DB类的时候关联表写入数据问题

laravel使用DB类的时候关联表写入数据问题:

使用门面的时候,要给当前用户设置角色,可以用$user->roles()->attach(1);如下所示:

    public function run()
    {
        $user=User::create([
            'name' => 'xiaoming',
            'email' => 'xiaoming@example.com',
            'password' => bcrypt('secret'),
            
        ]);
        $user->roles()->attach(1);
    }

问题:
现在要用DB类来完成上述功能,下面代码的$user->roles()->attach(1);不能运行,
会报错:

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to a member function roles() on boolean

应该怎么写才行?

    public function run()
    {
        $user=DB::table('users')->insert([
            'name' => 'xiaoming',
            'email' => 'xiaoming@example.com',
            'password' => bcrypt('secret'),
        ]);
        $user->roles()->attach(1);
    }
迷茫迷茫2687 天前337

全部回复(1)我来回复

  • 黄舟

    黄舟2017-05-16 16:49:37

    使用 DB 的时候,返回的是一个 bool 值:

    $user=DB::table('users')->insert([
                'name' => 'xiaoming',
                'email' => 'xiaoming@example.com',
                'password' => bcrypt('secret'),
            ]);
    $user->roles()->attach(1);

    $user 是一个 bool 值。

    回复
    0
  • 取消回复