简体   繁体   中英

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 ???

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM