dopq87915 2014-06-21 04:29
浏览 9
已采纳

在Laravel 4中,我无法在另一个连接中创建数据

the code can't create data

UserToken::on('user')->create($token_data);

result:{"error":{"type":"BadMethodCallException","message":"Call to undefined method Illuminate\Database\Query\Builder::create()","file":"F:\web\vgooo_laravel\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php","line":2094}}

and i try another code

$UserToken = new UserToken();
DB::connection('user')->table($UserToken->getTable())->insert($token_data);

result: success

why i can't use the "on" , is a bug

  • 写回答

1条回答 默认 最新

  • dongyun6229 2014-06-21 05:41
    关注

    From Laravel source for Illuminate\Database\Eloquent\Model:

    /**
     * Begin querying the model on a given connection.
     *
     * @param  string  $connection
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public static function on($connection = null)
    {
        // First we will just create a fresh instance of this model, and then we can
        // set the connection on the model so that it is be used for the queries
        // we execute, as well as being set on each relationship we retrieve.
        $instance = new static;
    
        $instance->setConnection($connection);
    
        return $instance->newQuery();
    }
    

    Your on() call returns an \Illuminate\Database\Eloquent\Builder but the create() method you are trying to call is only available in the Eloquent's Model class.

    You can do this instead:

    $user = new UserToken;
    $user->setConnection('user');
    $user->create($token_data);
    

    Or do it the Query Builder way:

    UserToken::on('user')->insert($token_data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路