robspin
robspin

Reputation: 811

Table name default is Table_s not Tables in laravel 5.5

When I use model A16 with eloquent

such as

php artisan db:seed

or other eloquent

$wantdata=A16::all

it shows

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'Db.A16_s'

I know I can fix with blow :

namespace App;

use Illuminate\Database\Eloquent\Model;

class tablename extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'A16s';
}

But how do I change the Tables for my default habits. And why I got A16_s not the A16s? I want to know how to fix it.

https://laravel.com/docs/5.6/eloquent the document write:

assume the Flight model stores records in the flights table

My laravel 5.5 default model.php write

 public function getTable()
    {
        if (! isset($this->table)) {
            return str_replace(
                '\\', '', Str::snake(Str::plural(class_basename($this)))
            );
        }

        return $this->table;
    }

why the default is snake case? how can I change it to the normal xxs name?

Upvotes: 0

Views: 396

Answers (1)

Ben
Ben

Reputation: 5129

If you look at getTable() definition, the table name defined at:

        return str_replace(
            '\\', '', Str::snake(Str::plural(class_basename($this)))
        );

It uses snake case and this is the reason why you got 'a16_s' instead of 'a16s'.

You can override the getTable() function if you want to have your own version, by inherit a custom model like this:

class tablename extends CustomModel
{
    ...
}


class CustomModel extends Model
{
    public function getTable()
    {
        if (! isset($this->table)) {
            // your own implementation here
        }
        return $this->table;
    }
}

or just define the $table variable or each model.

Upvotes: 1

Related Questions