douerqu2319 2019-07-22 13:01
浏览 197
已采纳

laravel ColumnDefinition类中的方法在哪里实现?

To write migrations in laravel, we have different methods to apply them to our $table columns. One of them, for example, is nullable() which makes that column nullable.

I want to know, where do functions like nullable() have been defined. I cannot see anything such as public function nullable() in laravel. This must be in one of these classes but I can not find it:

1) vendor\laravel\framework\src\Illuminate\Database\Schema\ColumnDefinition

2) vendor\laravel\framework\src\Illuminate\Support\Fluent

3) vendor\laravel\framework\src\Illuminate\Database\Schema\Blueprint

or any other class extended from these or any other trait used in one of these.

Where do these functions have been defined?

  • 写回答

2条回答 默认 最新

  • dongzi0850 2019-07-22 13:11
    关注

    The method nullable itself does not exist. If you take a look at the Blueprint class, the addColumn method returns an instance of ColumnDefinition.

    And ColumnDefinition is an empty class which simply extends the Fluent class that contains the following __call method:

    /**
     * Handle dynamic calls to the fluent instance to set attributes.
     *
     * @param  string  $method
     * @param  array   $parameters
     * @return $this
     */
    public function __call($method, $parameters)
    {
        $this->attributes[$method] = count($parameters) > 0 ? $parameters[0] : true;
    
        return $this;
    }
    

    Therefore, when you execute $table->string('name')->nullable();, it goes into the __call because the nullable method does not exist and simply saves the nullable attribute to true. Which also translates to:

    $this->attributes['nullable'] = true;
    

    And then in the MySqlGrammar class, it checks if the column is nullable or not:

    /**
     * Get the SQL for a nullable column modifier.
     *
     * @param  \Illuminate\Database\Schema\Blueprint  $blueprint
     * @param  \Illuminate\Support\Fluent  $column
     * @return string|null
     */
    protected function modifyNullable(Blueprint $blueprint, Fluent $column)
    {
        if (is_null($column->virtualAs) && is_null($column->storedAs)) {
            return $column->nullable ? ' null' : ' not null';
        }
    }
    

    For more information about __call: https://www.php.net/manual/en/language.oop5.overloading.php#object.call

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?