How to return database table name in Laravel

前端 未结 11 539
执念已碎
执念已碎 2020-12-28 13:28

Is there a way that I can get the current database table in use by the model that I\'m in? I see that there is a table() function in Laravel/Database/Eloquent/model.php but

相关标签:
11条回答
  • 2020-12-28 13:28

    Simple way to get table name from Laravel Model by this:

    $tableName = app(\App\User::class)->getTable();
    

    Don't forget to replace:

    \App\User

    With Model path.

    0 讨论(0)
  • 2020-12-28 13:30

    Edit April 2019: This answer is now out of date. See the new correct answer by Flyn San

    Yes - Eloquent has a $table variable. There are two ways you can access this:

    class yourModel extends Eloquent {
    
            public static $table = "differentTable";
    
            function someFunction()
            {
                 return yourModel::$table;
            }
    }
    

    or

    class yourModel extends Eloquent {
    
        public function someFunction()
        {
            return $this->table();
    
        }
    }
    

    then in your code

    Route::get('/', function () {
        $model = new yourModel();   
        dd($model->someFunction());
    });
    
    0 讨论(0)
  • 2020-12-28 13:30

    Based on tailor Otwell's answer you could use something like this:

    with(new Model)->getTable();
    

    Note: tested on versions 5.x, 6.x, 7.x, 8.x and it works well.

    0 讨论(0)
  • 2020-12-28 13:31

    In Laravel 4 use static method

    $table_name = Model::getTable();
    

    or "self" inside Eloquent Model

    $table_name = self::getTable();
    
    0 讨论(0)
  • 2020-12-28 13:32

    There is a public getTable() method defined in Eloquent\Model so you should be able to use $model->getTable().

    0 讨论(0)
  • 2020-12-28 13:33

    You can get name of a model's table in a static manner by following code:

    If we have a Model as ModelName:

    ModelName::query()->getQuery()->from
    

    This method also works fine in case of custom table name that are defined by protected $table = 'custom_table_name' in the Model.

    0 讨论(0)
提交回复
热议问题