kjdion84
kjdion84

Reputation: 10044

Eloquent using wrong table name

I have a model called ReferrerMedium along with a migration for a referrer_mediums table.

Here is my class:

namespace App;

class ReferrerMedium extends \Eloquent
{
    //
}

Here is my migration:

Schema::create('referrer_mediums', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
});

Here is my code:

foreach (ReferrerMedium::all() as $referrer_medium) {
    $options[$referrer_medium->name] = $referrer_medium->name;
}

This code is causing the error Base table or view not found: 1146 Table 'leadbind.referrer_media' doesn't exist

Why is it attempting to query the referrer_media table instead of referrer_mediums???

Upvotes: 0

Views: 2375

Answers (2)

Cong Chen
Cong Chen

Reputation: 2436

Because medium's plural type is media, therefore you should manually specified table name in you model:

protected $table = 'referrer_mediums';

But i recommend that you should make a migration to change the table name.

Upvotes: 5

Sagar Gautam
Sagar Gautam

Reputation: 9369

It's general definition standard that if you create a table with plural name and create model for this table as singular, then model automatically connects corresponding table, otherwise you should define table name in model like:

$protected $table = 'referrer_mediums';

In your case, Model name is ReferrerMedium so it will search for the singular of ReferrerMedium which is referrer_media that's the reason behind your problem.

So, either you can create table as referrer_media or define table name in model as above.

Hope you understand.

Upvotes: 3

Related Questions