Laravel:使用 Eloquent 模型时未配置数据库 [默认],但适用于 Facade

标签 laravel eloquent

我有一个模型可以扩展 Laravel 的 Eloquent 模型。当我尝试使用它时,出现错误 Database [default] not configured。但是,当我简单地调用 DB facade 时,它​​工作得很好。代码:

use Illuminate\Database\Eloquent\Model;

class Owners extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];
    protected $connection = 'default';

    public function records()
    {
        return $this->belongsTo(OwnersToRecords::class, 'owner_id', 'id');
    }

    public function zones()
    {
        return $this->belongsTo(OwnersToZones::class, 'record_id', 'id');
    }
}

当使用 $owner = new Owners 调用时,出现错误。当通过 DB::table('owners') 调用时,该表工作正常。那么,怎么了?

最佳答案

So, what's wrong?

这一行是错误的,因为在您的 config/database.php 文件中没有使用此名称的数据库连接。

protected $connection = 'default';

要么完全删除它,在这种情况下将使用默认连接,要么从您的配置文件中指定正确的数据库连接名称。

注意:除非您有非常具体的要求,即使用多个数据库或绝对需要一个单独的独立模型连接等。您不希望在您的模型中明确指定连接名称。

关于Laravel:使用 Eloquent 模型时未配置数据库 [默认],但适用于 Facade,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44506820/

相关文章:

php - 拉维尔 5.4 : Class 'App\Http\Controllers\Response' not found error

laravel-4 - Laravel 4.1 whereHas [违反完整性约束: 1052 Column 'confirm' in where clause is ambiguous ]

php - "Mass Assignment"在 Laravel 中是什么意思?

php - 如何使用外键约束为表添加种子 Laravel

css - 链接到 laravel + forge 中公用文件夹之外的 Assets

php - (Laravel) 基于用户输入的接口(interface)动态依赖注入(inject)

php - 如何在 laravel 中忽略某些有条件的字段的验证

laravel - 类 Illuminate\Support\Facades\RateLimiter 未找到

php - 带外键的 Laravel 存储模型

左连接的 Laravel 排序结果