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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?