我有一个模型可以扩展 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/